Last active
April 28, 2019 06:59
-
-
Save wheelerlaw/078c20b9c93ac1888606bbc360d2147d to your computer and use it in GitHub Desktop.
Split a PEM-formatted CA certificate chain into their individual certificates and place them in a temporary folder to use by other applications.
This file contains 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
#!/usr/bin/env bash | |
set -o pipefail | |
export cert_dir=$(mktemp -d -t certs.XXXXXXXXX) | |
trap 'rm -rf $cert_dir; trap - ERR EXIT' EXIT | |
cd $cert_dir | |
cat | csplit -z -s -f corporate-indv-cert- - '/-----BEGIN CERTIFICATE-----/' '{*}' | |
trap continue ERR | |
for cert in corporate-indv-cert-* | |
do | |
subject="#$(openssl x509 -noout -subject -in "$cert" | sed -n 's/ *commonName *= //p')" | |
issuer="#$(openssl x509 -noout -issuer -in "$cert" | sed -n 's/ *commonName *= //p')" | |
new_file_name=$(openssl x509 -noout -fingerprint -in "$cert" | sed -n 's/.*Fingerprint=//p') | |
new_file_name="${new_file_name//:/}" | |
# Handle non-numbered certs by numbering them. | |
# If there is only one other cert (that is likely not numbered) | |
if [[ -e "${new_file_name}.crt" ]]; then | |
>&2 echo "${new_file_name}.crt already exists" | |
file_num=2 | |
# If there are other numbered files. Get the highest one, and increment it. | |
if [[ $(ls ${new_file_name}-*.crt 2>/dev/null | grep -Eo '\-[0-9]+\.crt$' | grep -o '[0-9]*' | sort | tail -n1) != '' ]]; then | |
# List files that share the cert name, get the highest version. | |
file_num=$(ls ${new_file_name}-*.crt | grep -Eo '\-[0-9]+\.crt$' | grep -o '[0-9]*' | sort | tail -n1) | |
file_num=$((file_num + 1)) | |
fi | |
new_file_name="${new_file_name}-${file_num}" | |
fi | |
>&2 echo "Writing ${new_file_name}.crt" | |
mv $cert "${new_file_name}.crt" | |
echo "${subject}\n${issuer}\n$(cat ${new_file_name}.crt)" > ${new_file_name}.crt | |
done | |
trap - EXIT ERR | |
echo $cert_dir |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment