Created
October 18, 2015 02:42
-
-
Save gnanet/1d5929d64fb45904c32c to your computer and use it in GitHub Desktop.
Split combined PEM file the smart way (tested on debian, requires openssl)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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