How to extract the RSA public key from a .cer and store it in a .pem using OpenSSL?
101,545
Solution 1
Using this command I was able to generate the .pem
with the contents of the public key.
openssl x509 -inform der -in certificate.cer -pubkey -noout > certificate_publickey.pem
Which produces:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsM+whXrxmbCkPfkwY2EehYpIp
*blah blah blah blah*
-----END PUBLIC KEY-----
Solution 2
Solution for PowerShell:
$certFile = "[path to .cer file]"
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certFile)
$cer.PublicKey.Key.ToXmlString($false)
Solution from C#:
string certificate = @"<PATH TO .CER>";
X509Certificate2 cert = new X509Certificate2(certificate);
string xml = cert.GetRSAPublicKey().ToXmlString(false);
Comments
-
Steven Anderson almost 2 years
I have the requirement to extract the public key (RSA) from a
*.cer
file. I wish to extract the key and store it in a.pem
file so I can use its value to encrypt values using jsencrypt.The following command converts a
.cer
to.pem
:openssl x509 -inform der -in certificate.cer -out certificate.pem
Yet it doesn't generate a file with the public key but a file with the contents of the
*.cer
file.-----BEGIN CERTIFICATE----- MIICPDCCAamgAwIBAg............ *lots of extra contents* -----END CERTIFICATE-----
What command should I use to extract the public key and store it in a
.pem
file? -
Gobe almost 8 yearsThanks. Just a correction: for a .cer file input, the
inform
parameter should beder
-
Steven Anderson about 7 yearsI was pretty sure that what I wrote in my answer was correct and did work for me... I did use
-inform pem
. Although if-inform der
works too, then that's cool. -
Andrew Corkery over 6 yearsFor anyone else trying this,
-inform DER
would not work for me, but-inform PEM
works. -
Sergey Ponomarev over 4 yearsOMG I looked for this so long. This is mind blowing for me that instead of
-out
we should use-noout
with redirection to file. I tried to extract pub key from PEM file received from Google OAuth jwks_url v1 so now I finally did it. Thank you -
tresf almost 3 yearsAlthough the OP's intent is to use this with
jsencrypt
so his question was answered, it specifically asks about an RSA (PKCS#1) public key, but this answer appears to offer a PKCS#8 formatted public key. Is the OP's original question possible? The difference is the RSA public keys start withBEGIN RSA PUBLIC KEY
as opposed to the PKCS#8 which start withBEGIN PUBLIC KEY
. If I can find the answer on my own, I will supply it as an alternate solution. -
tresf almost 3 yearsThe solution to my question (RSA format, per OP's original request) is available here: stackoverflow.com/a/27930720/3196753