Skip to content

Instantly share code, notes, and snippets.

@genaromadrid
Last active January 29, 2024 11:38
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save genaromadrid/9075d315e949fb4b3760db5c36c9a8ca to your computer and use it in GitHub Desktop.
Save genaromadrid/9075d315e949fb4b3760db5c36c9a8ca to your computer and use it in GitHub Desktop.
Validate a Certificate against a Certificate Authority using OpenSSL

Certificate CA Validation

The easy way

To validate a certificate agains a certificate authority you just have to run

openssl verify -trusted ca_root.pem -untrusted intermediate_ca.pem certificate.pem

You'll see a 'OK' message at the end of the output

The hard way

cer=certificate.pem
sig_path=certificate.sig.bin
tbs_path=certificate.tbs
root_ca=intermediate_ca.pem
root_pub_key_path=intermediate_ca.key.pem

### Extract signature from certificate
# run the following and get the last bit position
openssl asn1parse -in $cer
last_bit_pos=819 # 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

### Get fingerprint of the signature, the fingerprint of the TBS Cert and compare them

# 1. Get the fingerprint of the signature with the root key
openssl rsautl -in $sig_path -verify -asn1parse -inkey $root_pub_key_path -pubin

# 2. Get the sha1 (or whatever algorithm was used) of the TBS Certificate
openssl sha1 -c $tbs_path

# Compare the signature fingerprint from step 1 with the sha1 of the tbs certificate. 
# if they match, the certificate was sign with the provided rootCa

### Other way to validate the certificate:
# Since the CA signed the DER format of the TBSCertificate, you can just 
# verify the signature of the certificate with the public key of the root 
# passing the TBSCertificate as a param
# If everything its fine you'll get a 'Verified OK' message or a 'Verification Failure' instead.
openssl dgst -sha1 -verify $root_pub_key_path -signature $sig_path $tbs_path

Notes

The TBS certificate is the body of the actual certificate; it contains all the naming and key information held in the certificate. The only information in the actual certificate that is not held in the TBS certificate is the name of the algorithm used to sign the certificate and the signature itself.

The TBS certificate is used as the input data to the signature algorithm when the certificate is signed or verified.

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment