Skip to content

Instantly share code, notes, and snippets.

@marinakr
Forked from gnanet/split-pem.sh
Last active June 4, 2019 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marinakr/937fccb46e357197e9b169bdf3e7fd2f to your computer and use it in GitHub Desktop.
Save marinakr/937fccb46e357197e9b169bdf3e7fd2f to your computer and use it in GitHub Desktop.
Split combined PEM file the smart way (tested on debian, requires openssl)
#!/bin/bash
CERT_NAME=cert_
META=.meta
#openssl pkcs7 -in ~/Downloads/PB2019.p7b -inform DER -print_certs -out chain.pem
if [ $1 ]
then
if [ -f $1 ]
then
pemfile=$1
fi
else
echo "Usage: split-pem.sh COMBINED-PEMFILE"
exit 1
fi
#clear meta
echo '' > $META
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
#split files
cnt=$(( $pemformatparts - 2 ))
csplit -k -f $CERT_NAME ${pemfile} '/END CERTIFICATE/+1' "{$cnt}"
for cert in $CERT_NAME*; do
hexname=$(openssl x509 -noout -subject -in $cert | sed -n 's/^.*CN=\(.*\)$/\1/; s/[ ,.*]/_/g; s/__/_/g; s/^_//g;p' || true).pem ;
subj=`echo -e $hexname | sed -e 's/[^A-Za-zА-я0-9._-]//g'`;
echo "$cert $subj" >> $META
done
echo "META $pemfile updated"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment