Converting PKCS#12 certificate into PEM using OpenSSL
Try:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes
After that you have:
- certificate in newfile.crt.pem
- private key in newfile.key.pem
To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:
openssl pkcs12 -in path.p12 -out newfile.pem -nodes
Or, if you want to provide a password for the private key, omit -nodes
and input a password:
openssl pkcs12 -in path.p12 -out newfile.pem
If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}
:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'
You just need to supply a password. You can do it within the same command line with the following syntax:
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]
You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes
More info: http://www.openssl.org/docs/apps/pkcs12.html
If you can use Python, it is even easier if you have the pyopenssl
module. Here it is:
from OpenSSL import crypto
# May require "" for empty password depending on version
with open("push.p12", "rb") as file:
p12 = crypto.load_pkcs12(file.read(), "my_passphrase")
# PEM formatted private key
print crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
# PEM formatted certificate
print crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
I had a PFX file and needed to create KEY file for NGINX, so I did this:
openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes
Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----
. After that NGINX accepted the KEY file.