Created
April 30, 2016 23:14
-
-
Save wpalmer/4ed6b6784261ad5c79dc1ae3a6d2f4ea to your computer and use it in GitHub Desktop.
Split a combined SSL certificate file into component parts (key and individual certificates)
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
#!/bin/bash | |
TEMP="$(mktemp --tmpdir -d 'ssl.XXXXXXXXXX')" | |
[ -n "$TEMP" -a -d "$TEMP" -a -w "$TEMP" ] || exit 1 | |
_cleanup(){ rm -rf "$TEMP"; } | |
trap _cleanup EXIT | |
file="$1" | |
cert="$TEMP/cert" | |
now="$(date --utc +'%Y%m%d%H%M%S')" | |
i=1 | |
site= | |
allvalid=1 | |
dates= | |
while read -r line; do | |
[[ "$line" = "" ]] && continue | |
if [[ "$(sed 's#^--* *\(END\) .*#\1#' <<<"$line")" = "END" ]]; then | |
printf '%s\n' "$line" >> "$cert" | |
type="$(sed 's#^--* *END \([^-][^-]*\)--*#\1#' <<<"$line")" | |
case "$type" in | |
RSA\ PRIVATE\ KEY) | |
cat "$cert" > "$TEMP/key" | |
;; | |
CERTIFICATE\ REQUEST) | |
allvalid=0 | |
> "$cert" | |
;; | |
CERTIFICATE) | |
CN="$(openssl x509 -in "$cert" -subject -noout | sed 's#^subject=.*CN=\([^/]*\).*$#\1#;')" | |
label="${CN//./-}" | |
startdate="$(date --utc -d "$(openssl x509 -in "$cert" -startdate -noout | sed 's#^[^=]*=##')" +'%Y%m%d%H%M%S')" | |
enddate="$(date --utc -d "$(openssl x509 -in "$cert" -enddate -noout | sed 's#^[^=]*=##')" +'%Y%m%d%H%M%S')" | |
valid=OK | |
[[ $now -lt $startdate ]] && valid=PREMATURE | |
[[ $now -gt $enddate ]] && valid=EXPIRED | |
[[ "$valid" = "OK" ]] || allvalid=0 | |
if [[ ! "$CN" = "$label" ]]; then | |
site="$label" | |
dates="$startdate-$enddate" | |
fi | |
#printf '%s\n' "$file.$i $label / $CN $startdate - $enddate $valid" >&2 | |
#openssl x509 -in "$cert" -text -noout >&2 | |
cat "$cert" > "$TEMP/cert.$i" | |
i="$(( $i + 1 ))" | |
> "$cert" | |
;; | |
*) | |
printf 'Unknown Certificate Part (%s.%d) Type: %s\n' "$file" "$i" "$type" >&2 | |
allvalid=0 | |
> "$cert" | |
;; | |
esac | |
else | |
printf '%s\n' "$line" >> "$cert" | |
fi | |
done < "$file" | |
rm -f "$TEMP/cert" | |
if [[ "$allvalid" = "1" ]] && [[ -n "$site" ]]; then | |
cat "$TEMP/cert".* > "t/$site.$dates.crt" | |
cat "$TEMP/key" > "t/$site.$dates.key" | |
echo "$site" >&2 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment