'How to check a public RSA key file

Inside a shell script I want verify public RSA file. All I want to do is that find a way to check this file is a genuine public key file, nothing else.

Can I ask experts here what are the ways I can verify this input file to check this is a genuine public key file , not a regular file.

I will be using this public key file in future to validate an incoming encrypt gzip file but that is out of scope for now.

All I want is validate input file to check its genuine RSA public key file not an ordinary file.please note that I do not have any other files with me (eg : private key) .

e.g.: if the file is ‘public.pem’ I just want check inside that it’s a genuine RSA public key file not just a file with texts or file is not corrupted . I’m already checking that file is not zero sized and md5 .

other possible checks I found check file got text ‘BEGIN PUBLIC KEY’ and ‘END PUBLIC KEY’ Also found this command in google , Is there a better way to do this using openssl

‘openssl rsa -noout -text -inform PEM -in pubkey.pem -pubin’

Thanks



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Try this command if your public key starts with -----BEGIN RSA PUBLIC KEY-----

openssl rsa -RSAPublicKey_in -in /path/to/pub_key.pem -noout -text

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alain O'Dea
Solution 3 Quanlong