How to check a public RSA key file

The following script should work for all PEM-formatted keys and certs supported by OpenSSL. I have tested it on various valid and invalid ECDSA and RSA keys with matching and non-matching certs.

Save this as verify-cert-key:

#!/usr/bin/env bash
certFile="${1}"
keyFile="${2}"
certPubKey="$(openssl x509 -noout -pubkey -in "${certFile}")"
keyPubKey="$(openssl pkey -pubout -in "${keyFile}")"
if [[ "${certPubKey}" == "${keyPubKey}" ]]
then
  echo "PASS: key and cert match"
else
  echo "FAIL: key and cert DO NOT match"
fi

Make it executable:

chmod +x verify-cert-key

Run it on a cert and key:

./verify-cert-key server-crt.pem server-key.pem

It's possible to use any public key format parser, including openssl or even parse key yourself as the format is not that difficult.

Command line tools set a non-zero exit code, when parsing fails:

openssl rsa -inform PEM -pubin -in pubkey.pem -noout &> /dev/null
if [ $? != 0 ] ; then
    echo "this was definitely not a RSA public key in PEM format"
    exit 1
fi

Just to check any public key:

openssl pkey -inform PEM -pubin -in pubkey.pem -noout &> /dev/null
if [ $? != 0 ] ; then
    echo "this was definitely not a public key in PEM format"
    exit 1
fi