I always need to look at the man page of OpenSSL or review my bash history to use the right options to extract a certificate file and a key file from it.
For this reason, I’ve created a small bash script to complete this step for me.
I used this script mainly on Linux, but can be very useful even on Windows using WSL (with any distribution). It is simply a matter of opening file explorer on the folder where the pfx is stored, copy the script and run it in place, so the files will be quickly generated there.
How it works and what it does?
This bash script requires OpenSSL and zip (both included in any standard Linux distribution). It will prompt the user to type the certificate (certificate + private key) file name with pfx extension, prompt also to type your passphrase (if it was implemented to protect the private key) and finally it will generate individual files for:
- certificate.pem (certificate with no private key)
- key.pem (just private key protected with a password)
- certificate.key (just private key without password)
- certificate.zip (will all the files above including the pfx)
# THIS SCRIPT EXTRACT A CERTIFICATE AND PRIVATE KEY FROM PFX FILE
# Paolo Frigo, https://www.scriptinglibrary.com
read -p "Certificate name (e.g. MyCert.pfx):" PfxCert
#Export the private key
openssl pkcs12 -in $PfxCert -nocerts -out key.pem -nodes
#Export the certificate
openssl pkcs12 -in $PfxCert -nokeys -out $CertName.pem
#Remove the passphrase from the private key
openssl rsa -in key.pem -out $CertName.key
#Create a Zip file
zip $CertName.zip $CertName.pem key.pem $CertName.key $PfxCert
echo "$CertName.pem, key.pem and $CertName.key generated from $PfxCert"
echo "All files added to a zip archive $CertName.zip"
I don’t install SSL Certificates every single day, Let’s Encrypt and Certbot/Acme tools reduced a lot this activity for me in these recent years. But pfx is definitely the most common format I use when I purchase one, so whenever I need to configure for instance an Apache webserver this script it is quite handy.
As usual, you can find this script on my GitHub repository.