Skip to content

Instantly share code, notes, and snippets.

@jonasbjork
Created February 13, 2019 14:18
Show Gist options
  • Save jonasbjork/af033dd48988555557a7b879464bce88 to your computer and use it in GitHub Desktop.
Save jonasbjork/af033dd48988555557a7b879464bce88 to your computer and use it in GitHub Desktop.
Convert PFX certificates to PEM format
#!/usr/bin/env bash
#
# Convert PFX certficates to PEM format
# Jonas Björk, jonas.bjork@gmail.com
# Helsingborg, Sweden, 2019-02-13
#
echo "> PFX to PEM certificate converter"
# If no certificate file is stated, bail out with syntax help
if [ $# -eq 0 ] ; then
echo "Syntax: ${0} pfx_file"
exit 1
fi
# If input certificate does not exist, there is no use of continue this
ORIG_CERT=${1}
echo "| Original certificate (PFX): ${ORIG_CERT}"
if [ ! -f ${ORIG_CERT} ] ; then
echo "! Error: ${ORIG_CERT} not found!"
exit 1
fi
# Make sure we have an output directory
if [ ! -d "out/" ] ; then
echo "| Creating out/ directory"
mkdir out
fi
# Get the certificate name without extension (.pfx)
CERT_NAME=${ORIG_CERT%.*}
# Make some sanity checks, DO NOT OVERWRITE existing certs
if [ -f out/${CERT_NAME}.pem ] ; then
echo "! File: out/${CERT_NAME}.pem already exists! I do not touch it!"
exit 1
fi
if [ -f out/${CERT_NAME}.key ] ; then
echo "! File: out/${CERT_NAME}.key already exists! I do not touch it!"
exit 1
fi
echo "| #1 : You must specify the password for the certificate you are importing!"
openssl pkcs12 -in ${ORIG_CERT} -clcerts -nokeys -out out/${CERT_NAME}.pem
echo "| #2 : ...and import password again, this time we are creating the key"
echo "> PEM pass phrase is the pass phrase you want for the new certficate"
openssl pkcs12 -in ${ORIG_CERT} -nocerts -out out/${CERT_NAME}.tmpkey
echo "| #3 : .. finally we are making the new key pass phrase less"
echo "> Use the pass phrase you just set up in the second step."
openssl rsa -in out/${CERT_NAME}.tmpkey -out out/${CERT_NAME}.key
rm out/${CERT_NAME}.tmpkey
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment