Linux: openssl to validate whether private key and TLS certificate match

In environments where certificates are manually deployed, reloading TLS certs is often only done annually when the certificate is near expiration.  This long lapse in time often means that someone else has inherited the task of renewal, and the original key in use may even be in question.

Luckily, openssl provides a way to validate whether a private key and public TLS certificate are matched.

# variables for private key and public certificate
keyFile=my.key
certFile=my.pem

# match of md5 hash proves the key and cert are a pair
openssl rsa -noout -modulus -in $keyFile | openssl md5
openssl x509 -noout -modulus -in $certFile | openssl md5

Furthermore, if there is a custom root CA, you can test for the public certificate being a valid descendant.

caFile=myca.pem
# will respond with "OK" if match, exit code=1 and "Error loading file" if mismatch
openssl verify -CAfile $caFile $certFile

Here is my github script openssl_key_cert_check.sh that contains this logic.

REFERENCES

letsencrypt.org, avoid needing manual renewals

github, script that does key/certificate validation and CA check

fabianlee, ssh-keygen to check validity of ssh key and public cert pair