Inside a shell script I want verify a public RSA file public.pem
.
All I want is to check that this file is a genuine public RSA key file, nothing else, like a regular file or a corrupted key.
I will be using this public key file in the future to validate an incoming encrypted gzip file but that is out of scope for now.
Please note that I do not have any other files with me (e.g., a private key).
I’m already checking that file is not zero-sized and I use MD5.
Another possible check I found is that the file contains the text BEGIN PUBLIC KEY
and END PUBLIC KEY
.
Also I found this command with Google:
openssl rsa -noout -text -inform PEM -in pubkey.pem -pubin
Is there a better way to do this using openssl
?
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