Creating RSA Private Key from PFX (PKCS #12) file

Dorana picture Dorana · Sep 14, 2012 · Viewed 35.7k times · Source

I'm trying to get a private RSA key from a pkcs #12 file.

I've tried running the standard

openssl pkcs12 -nocerts -out priv.pem -in domain.com.pfx

However this results in a key file like the one below:

Bag Attributes
Microsoft Local Key set: <No Values>
localKeyID: 01 00 00 00 
friendlyName: xxxxxxxx
Microsoft CSP Name: Microsoft RSA SChannel Cryptographic Provider
Key Attributes
X509v3 Key Usage: 10
-----BEGIN ENCRYPTED PRIVATE KEY-----

The server that I need to put it into canot handle the key file, and when I look at the examples data I see a file like below

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,2CF27DD60B8BB3FF

And of cause the key is present in both files. However it seems the server will only accept RSA Private key file, and it seems to me like the output I get is a X509v3 file, any one know how to get this to an RSA Private key file?

Answer

Dirk-Willem van Gulik picture Dirk-Willem van Gulik · Sep 14, 2012

Well - using a text editor to remove the offending lines may be easiest. Otherwise below will clean up the bag attributes:

openssl pkcs12 -in x.pfx  -nocerts -nodes -passin pass:123456 | openssl rsa -out privkey.pem

and can also be used to get der/net

openssl pkcs12 -in x-fred.p12  -nocerts -nodes -passin pass: | openssl rsa -outform DER -out privkey.der

which may be in fact the format you want. It is fairly common for tools to not accept a password less private key though (and a lot of tools will silently fail if the # of chars are not at least 4 or 6). So in those cases change the tailend to:

.... | openssl rsa -passout pass:123456 -out privkey.pem
.... | openssl rsa -passout pass:123456 -out privkey.der -outform der