Extract PEM Public Key from X.509 Certificate

legoblocks picture legoblocks · Mar 14, 2015 · Viewed 22.4k times · Source

I've created what I believe is a certificate containing a Public Key DER file, but I need the Public Key in PEM format now for a different platform. The aim is to use the same public key.

I created it using RSA Encryption in iOS and Decrypt It Using PHP:

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650

I have an existing public key in use (public_key.der) and can't change it. However I now need a PEM version of the public key

public_key.pem

How can I convert from DER to PEM in this way?

Note: If I had created my keypair using the following method, things would be easy. I could extract a public key PEM file:

openssl genrsa -out rsa.pem 1024 
openssl rsa -in rsa.pem -pubout

Public PEM files generated this way work. Is it possible that what I've created eariler on (with the -x590 command) are entirely different creatures to the output of the rsa commands?

Answer

divanov picture divanov · Mar 14, 2015

Assuming you've created certificate in DER format with the command

openssl req -x509 -out certificate.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650

Then extracting public key in PEM format can be done with a command

openssl x509 -inform der -in certificate.der -pubkey -noout > public_key.pem

-inform defines certificate format (default is PEM) and -noout suppresses output except of requested -pubkey.

The same operation with certificate in PEM format:

openssl x509 -in certificate.pem -pubkey -noout > public_key.pem