Skip to content

Instantly share code, notes, and snippets.

@felix
Last active June 26, 2024 05:40
Show Gist options
  • Save felix/291a3824c3e148bfdca3d324454a69f4 to your computer and use it in GitHub Desktop.
Save felix/291a3824c3e148bfdca3d324454a69f4 to your computer and use it in GitHub Desktop.
Verify x509 PEM certificate with its issuer
#!/bin/sh
set -e
usage() {
printf 'usage: %s <issuer.pem> <certificate.pem>\n' "$(basename "$0")"
exit 1
}
CA_FILE=$1
CERT_FILE=$2
[ -z "$CA_FILE" ] && usage
[ -z "$CERT_FILE" ] && usage
TMPDIR="$(mktemp -d)"
SIG_FILE="$TMPDIR/signature.bin"
TBS_FILE="$TMPDIR/tbs.bin"
PUBKEY_FILE="$TMPDIR/ca.pubkey.pem"
trap 'rm -rf -- "$TMPDIR"' EXIT
# Determine the signature offset
last_bit_pos="$(openssl asn1parse -in "$CERT_FILE" |tail -n1 |cut -d: -f1)"
# Extract signature from certificate
openssl asn1parse -in "$CERT_FILE" -out "$SIG_FILE" -noout -strparse "$last_bit_pos"
# Extract the public key of the CA
openssl x509 -in "$CA_FILE" -pubkey -noout > "$PUBKEY_FILE"
# Extract the tbs data
openssl asn1parse -in "$CERT_FILE" -out "$TBS_FILE" -noout -strparse 4
# Determine the signature hash algorithm
sigAlg="$(openssl x509 -text -noout -in $CERT_FILE |grep "Signature Algorithm" |tail -n1 |grep -Eio 'sha[0-9]+')"
# Verify the signature against the tbs data using the public key
openssl pkeyutl -verify -sigfile "$SIG_FILE" -inkey "$PUBKEY_FILE" -in "$TBS_FILE" -pubin -rawin -digest "$sigAlg"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment