Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract RSA public key from a x509 char array with openssl

Tags:

c

openssl

Here is a certificate in x509 format that stores the public key and the modulo:

const unsigned char *certificateDataBytes = {/*data*/};

Using OpenSSL and C, how can I convert it into an RSA object? I've tried several methods but I can't get it to work in RSA_public_encrypt

like image 420
blake305 Avatar asked Dec 15 '22 12:12

blake305


1 Answers

I think you mean public key into RSA * structure.

Since, you have certificate in bytes, if it is in DER encoded bytes, then you need to first convert it into X509 * structure.

 X509 * cert;
 EVP_PKEY * pubkey;
 //length is the length of the certificateDataBytes in terms of bytes.
 cert = d2i_x509 (NULL, certificateDataBytes, length);
 pubkey = X509_get_pubkey (cert);

Please note that if certificate has RSA public key, then you can get RSA public key as follows:

 RSA * rsa
 rsa = EVP_PKEY_get1_RSA(pubkey);

 //Now rsa contains RSA public key. Use it.

 //After use, free the pubkey
 EVP_PKEY_free (pubkey);

I hope this must solve your purpose. If certificate encoding is different, use different function. Once, you get X509 *, rest step is same.

like image 104
doptimusprime Avatar answered Dec 18 '22 01:12

doptimusprime