Is there an easy way to verify that a given private key matches a given public key? I have a few *.pub
and a few *.key
files, and I need to check w
For DSA keys, use
openssl dsa -pubin -in dsa.pub -modulus -noout
to print the public keys, then
openssl dsa -in dsa.key -modulus -noout
to display the public keys corresponding to a private key, then compare them.
Delete the public keys and generate new ones from the private keys. Keep them in separate directories, or use a naming convention to keep them straight.
I found a way that seems to work better for me:
ssh-keygen -y -f <private key file>
That command will output the public key for the given private key, so then just compare the output to each *.pub file.
I always compare an MD5 hash of the modulus using these commands:
Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5
If the hashes match, then those two files go together.
If it returns nothing, then they match:
cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost
The check can be made easier with diff:
diff <(ssh-keygen -y -f <private_key_file>) <public key file>
The only odd thing is that diff says nothing if the files are the same, so you'll only be told if the public and private don't match.