How to save public key in SSL certificate messages using OpenSsl?
I want to save the public key and its algorithm in SSL Certificates messages.
in OpenSSL library, I found a function named public_key_type which returns public key algorithm. but to extract public key, I found just a function named evp_PKEY_print_public, which prints public key. but I don't want to print it. my goal is to save it in a structure. anyone can help me?
1 answer

From your question, it is not entirely clear to me what you mean by "to save it in a structure". But I can explain how you can get access to the actual public key stored in your certificate, so you can do what you want with it.
First, you can use the following to get a hold of the certificate's public key, in its generic format:
EVP_PKEY *pubkey = X509_get_pubkey(cert); /* If it is not NULL, do what needs to be done with pubkey */ EVP_PKEY_free(pubkey);
See the documentation of
X509_get_pubkey()
for more information.Now that you have this generic public key, you can use its lowerlevel key accessors to get access to the underlying public key in its specific format. For example:
RSA *rsapubkey = EVP_PKEY_get1_RSA(pubkey); if (NULL != rsapubkey) { printf("This cert has an RSA public key\n"); /* Do your stuff with the RSA key, for example using RSA_get0_key() */ RSA_free(rsapubkey); }
The function
EVP_PKEY_get1_RSA()
returnsNULL
if the underlying key is not an RSA key. Otherwise, you can use it to get access to the modulo (n
) and exponent (e
), which is basically all you need to "save" it. Or you can hold on torsapubkey
, since it contains all public key information. You have toRSA_free()
it when you are done.Similarly, you can use
EVP_PKEY_get1_EC_KEY()
if you expect an EC key.