Check if SSL certificate matches private key (BASH)

Sometimes you need to double check that a private key matches your certificate (if, for example, you've got multiple badly named keys on your system). You might also occasionally want to check if a certificate matches a Certificate Signing Request (CSR)

Details

  • Language: BASH

Snippet

# Compare certificate to key
#
# You should see one hash. If two hashes are displayed, they don't match
$( openssl x509 -noout -modulus -in server.crt | openssl md5 ;\
openssl rsa -noout -modulus -in server.key | openssl md5 ) |  uniq

# Compare CSR to cert
$( openssl x509 -noout -modulus -in server.crt | openssl md5 ;\
openssl req -noout -modulus -in server.csr | openssl md5 ) |  uniq

Usage Example

hashes=`$( openssl x509 -noout -modulus -in server.crt | openssl md5 ;\
openssl rsa -noout -modulus -in server.key | openssl md5 ) | uniq | wc -l`

if [ $hashes -gt 1 ]
then
    echo "Does not match"
else
    echo "Matches"
fi