Skip to content

Instantly share code, notes, and snippets.

@gnanet
Created October 18, 2015 02:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gnanet/1d5929d64fb45904c32c to your computer and use it in GitHub Desktop.
Save gnanet/1d5929d64fb45904c32c to your computer and use it in GitHub Desktop.
Split combined PEM file the smart way (tested on debian, requires openssl)
#!/bin/bash
if [ $1 ]
then
if [ -f $1 ]
then
pemfile=$1
fi
else
echo "Usage: split-pem.sh COMBINED-PEMFILE"
exit 1
fi
pemformatparts=`grep -E "BEGIN.*PRIVATE KEY|BEGIN CERT" ${pemfile} 2> /dev/null | wc -l`
if [ ${pemformatparts} -lt 2 ]
then
echo "ERROR: ${pemfile} is not combined PEM format"
exit 1
fi
getcn=`/usr/bin/openssl x509 -noout -subject -in ${pemfile} | sed -e "s/.*CN=//g" -e "s/\/.*//g"`
if [ "${getcn}" == "" ]
then
pembase=${pemfile%%????}
else
echo "Retrieved CN, using ${getcn} as basename"
pembase=${getcn}
fi
# Extract key
echo -n "Extracting key ${pembase}.key "
/usr/bin/openssl pkey -in ${pemfile} -out ${pembase}.key || {
echo "FAILED"
exit 1
}
echo "DONE"
# Extract cert
echo -n "Extracting certificate ${pembase}.crt "
#/usr/bin/openssl x509 -in ${pemfile} -outform DER -out ${pembase}.der.crt
/usr/bin/openssl x509 -in ${pemfile} -outform PEM -out ${pembase}.crt || {
echo "FAILED"
exit 1
}
echo "DONE"
# Extract chain
echo -n "Extracting certificate chain ${pembase}-chain.crt "
/usr/bin/openssl crl2pkcs7 -nocrl -certfile ${pemfile} | /usr/bin/openssl pkcs7 -print_certs -out ${pembase}-chain.crt || {
echo "FAILED"
exit 1
}
echo "DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment