Skip to content

Instantly share code, notes, and snippets.

@brodygov
Created June 15, 2018 21:52
Show Gist options
  • Save brodygov/f34bbeb976cffc27eba36e0d9a6a6f69 to your computer and use it in GitHub Desktop.
Save brodygov/f34bbeb976cffc27eba36e0d9a6a6f69 to your computer and use it in GitHub Desktop.
Import certificate authorities into a repo while normalizing their format and finding duplicates
#!/bin/bash
set -eu
usage() {
cat >&2 <<EOM
usage: $(basename "$0") CRT_FILE BASENAME
Import CRT_FILE (in PEM format) into this directory with BASENAME as the
prefix. The output file will be named in this format:
BASENAME.<issue_year>-<exp_year>.<subj_key_id>.<sha1_fingerprint>.crt
EOM
}
run() {
echo >&2 "+ $*"
"$@"
}
not_clobbering() {
if [ -e "$1" ]; then
echo >&2 "already exists: $1"
return 1
else
return 0
fi
}
if [ $# -ne 2 ]; then
usage
exit 1
fi
crt_file="$1"
basename="$2"
text="$(run openssl x509 -in "$crt_file" -noout -text -fingerprint)"
subj_key_id="$(echo "$text" | grep -A 1 "X509v3 Subject Key Identifier" | tail -1 | tr -d ' :')"
fingerprint="$(echo "$text" | tail -1 | grep SHA1 | cut -d'=' -f2 | tr -d ':')"
validity="$(echo "$text" | grep -A 2 -E '^ *Validity *$')"
issue_year="$(echo "$validity" | grep 'Not Before:' | awk '{ print $(NF-1)}')"
exp_year="$(echo "$validity" | grep 'Not After :' | awk '{ print $(NF-1)}')"
out_suffix="${issue_year}-${exp_year}.${subj_key_id:0:8}.${fingerprint:0:8}.crt"
out_name="$basename.$out_suffix"
out_dir="$(dirname "$0")"
if [ -e "$out_dir"/*".$out_suffix" ]; then
echo >&2 "error: certificate seems to be already found:"
ls -ld "$out_dir"/*".$out_suffix"
exit 3
fi
out_path="$out_dir/$out_name"
echo "$crt_file -> $out_path"
# ensure atomic write
set -o noclobber
if not_clobbering "$out_path"; then
openssl x509 -in "$crt_file" > "$out_path"
fi
if not_clobbering "$out_path.txt"; then
openssl x509 -in "$crt_file" -text > "$out_path.txt"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment