Skip to content

Instantly share code, notes, and snippets.

@mbomb007
Forked from whereisaaron/pfx-to-crt-and-key.sh
Last active January 3, 2024 20:23
Show Gist options
  • Save mbomb007/68e4e662027c72736826f1abf7b2cde9 to your computer and use it in GitHub Desktop.
Save mbomb007/68e4e662027c72736826f1abf7b2cde9 to your computer and use it in GitHub Desktop.
Extract a crt, key, pem, and chain bundle from a PFX file, prompts for password or use PFXPASSWORD environment variable
#!/bin/bash
#------------------
# Extract the key, pem, certficiate, and chain from a PFX file
#
# https://gist.github.com/mbomb007/68e4e662027c72736826f1abf7b2cde9
#
# Must supply the input pfx file
PFX_PATH="$1"
if [ "${PFX_PATH}" == "" ]; then
echo "Must supply pfx file path"
exit 1
fi
# Read password if not in environment variable
if [[ ! ${PFXPASSWORD+x} ]]; then
echo -n "Password: "
read -s PFXPASSWORD
echo
export PFXPASSWORD
fi
# Option supply a prefix for the output files
FILENAME=$(basename "$PFX_PATH")
if [ "$2" != "" ]; then
FILENAME_BASE=$2
else
FILENAME_BASE="${FILENAME%.*}"
fi
echo "Using '${FILENAME_BASE}' as base for output filenames"
#
# Extract key, certificate, and chain, going to extra steps to remove the 'Bag attributes'
# Note that openssl dumps the chain in the wrong order! (Anyone have fix?)
#
# If you don't want to remove bag attributes, remove the pipe to openssl
# `| openssl rsa` or `| openssl x509`.
#
echo "Extracting ${FILENAME_BASE}.key"
openssl pkcs12 -in "$PFX_PATH" -nocerts -nodes -passin env:PFXPASSWORD \
-out "${FILENAME_BASE}.key"
echo "Extracting ${FILENAME_BASE}.crt"
openssl pkcs12 -in "$PFX_PATH" -nokeys -clcerts -nodes -passin env:PFXPASSWORD \
-out "${FILENAME_BASE}.crt"
echo "Extracting ${FILENAME_BASE}-ca-bundle.crt"
openssl pkcs12 -in "$PFX_PATH" -nokeys -cacerts -nodes -passin env:PFXPASSWORD \
| grep -v -e '^\s' | grep -v '^\(Bag\|subject\|issuer\)' > "${FILENAME_BASE}.ca-bundle"
# Check if the bundle actually has any certificates
if [[ ! -s "${FILENAME_BASE}.ca-bundle" && -f "${FILENAME_BASE}.ca-bundle" ]]; then
echo "Bundle ${FILENAME_BASE}.ca-bundle is empty, deleting"
rm "${FILENAME_BASE}.ca-bundle"
fi
echo "Creating ${FILENAME_BASE}.pem"
cat "${FILENAME_BASE}.key" "${FILENAME_BASE}.crt" "${FILENAME_BASE}.ca-bundle" > "${FILENAME_BASE}.pem"
echo "Done."
@mbomb007
Copy link
Author

mbomb007 commented Jan 3, 2024

Note that the ca-bundle file will probably be given in the reverse order, and with the anchor cert. ssllabs.com will complain about both. To fix them both, remove the 2nd from the last CERTIFICATE block from the resulting .pem file (which was the first block in the ca-bundle file.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment