Why I can’t read openssl generated RSA pub key with PEM_read_RSAPublicKey

cencryptionopensslrsa

I'm trying to read a RSA public key generated with openssl like this:

Private Key:
    openssl genrsa -out mykey.pem 1024

Public Key afterwards:
    openssl rsa -in mykey.pem -pubout > somewhere.pub

Then I try to read:

FILE *keyfile = fopen("somewhere.pub", "r");
RSA *rsa_pub = PEM_read_RSAPublicKey(keyfile, NULL, NULL, NULL);
//rsa_pub == NULL!

When I'm reading the private key it works

FILE *keyfile = fopen("mykey.pem", "r");
RSA *rsa_pri = PEM_read_RSAPrivateKey(keyfile, NULL, NULL, NULL);
//all good

Any ideas?

I've read that openssl generate a X509 key of the RSA public key. But I could not manage to load even a X509 pub key.

Thanks

Best Answer

You might try PEM_read_RSA_PUBKEY() instead of PEM_read_RSAPublicKey().

This is all about formats.

The default public key file format generated by openssl is the PEM format.

PEM_read_RSA_PUBKEY() reads the PEM format. PEM_read_RSAPublicKey() reads the PKCS#1 format.

So if you want to stick to PEM_read_RSAPublicKey() you could generate the public key file using the PKCS#1 format by specifying the -outform DER option when generating the public key.