Skip to content

Instantly share code, notes, and snippets.

@genaromadrid
Last active May 12, 2016 04:38
Show Gist options
  • Save genaromadrid/fd21c3cadaf769b99eb44a1af0f34e06 to your computer and use it in GitHub Desktop.
Save genaromadrid/fd21c3cadaf769b99eb44a1af0f34e06 to your computer and use it in GitHub Desktop.
Validate a Certificate against a Certificate Authority using OpenSSL
#!/usr/bin/env bash
set -o errexit
set -o pipefail
cer=null
root_ca=null
usage ()
{
echo "Usage: $0 options"
echo
echo " -c, --cer [required] Certificate to validate"
echo " -ca, --rootCA [required] Root Certificate Authority to validate against"
echo
exit
}
while :; do
case "$1" in
-c | --cer)
cer="$2"
shift 2
;;
-ca | --rootCA)
root_ca="$2"
shift 2
;;
--) # End of all options
shift
break
;;
-*)
echo "Error: Unknown option: $1" >&2
usage
exit 1
;;
*) # No more options
break
;;
esac
done
if [ "$cer" = 'null' ]; then
echo "Error: Please provide a cer file"
usage
fi
if [ "$root_ca" = 'null' ]; then
echo "Error: Please provide a rootCA file"
usage
fi
sig_path=$(mktemp)
tbs_path=$(mktemp)
root_pub_key_path=$(mktemp)
### Extract signature from certificate
# run the following and get the last bit position
# openssl asn1parse -in $cer
last_bit_pos=$(openssl asn1parse -in $cer | tail -1 | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//')
# Put your own
openssl asn1parse -in $cer -out $sig_path -noout -strparse $last_bit_pos
### Extract the public key of the root CA
openssl x509 -in $root_ca -pubkey -noout > $root_pub_key_path
### Extract the TBSCertificate
# Almost always -strparse param is 4
openssl asn1parse -in $cer -out $tbs_path -noout -strparse 4
openssl dgst -sha1 -verify $root_pub_key_path -signature $sig_path $tbs_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment