How to check open RSA key file

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

May I ask the experts how I can check this input file to verify that it is a real public key file, not a regular file.

I will use this public key file in the future to check the incoming gzip file for encryption, but it is not available at the moment.

All I want to do is check the input file to check its genuine RSA public key is not a regular file. Please note that I do not have other files with me (for example: private key).

For example: if the file is 'public.pem' , I just want to check inside that its genuine RSA public key file is not just a file with text or a file is not damaged. I already verify that the file is not null and md5.

other possible checks that I found check the resulting file '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

+8
shell openssl rsa public-key pem
source share
2 answers

You can use any public key parser, including openssl or even the parsing itself, since the format is not so difficult.

Command line tools set a non-zero exit code when parsing is not performed:

 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 verify 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 
+17
source share

The following script should work for all keys and certificates in the PEM format supported by OpenSSL. I tested it on various valid and invalid ECDSA and RSA keys with corresponding and non-corresponding certificates.

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 the certificate and key:

 ./verify-cert-key server-crt.pem server-key.pem 
0
source share

All Articles