Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract PEM Public Key from X.509 Certificate

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?

like image 363
legoblocks Avatar asked Mar 14 '15 13:03

legoblocks


People also ask

Can you extract public key from certificate?

When you create a certificate, you can specify whether it is exportable. If a key is exportable, it can be extracted and put in a file along with the associated certificate.

How can I get private key from x509 certificate?

Right-click the openssl.exe file and select Run as administrator. Enter the following command to begin generating a certificate and private key: req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout privateKey. key -out certificate.


1 Answers

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
like image 82
divanov Avatar answered Sep 30 '22 00:09

divanov