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
Enter the following command to check if a private key and public key are a matched set (identical) or not a matched set (differ) in $USER/.ssh directory. The cut command prevents the comment at the end of the line in the public key from being compared, allowing only the key to be compared.
ssh-keygen -y -f ~/.ssh/id_rsa | diff -s - <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
Output will look like either one of these lines.
Files - and /dev/fd/63 are identical
Files - and /dev/fd/63 differ
I wrote a shell script that users use to check file permission of their ~/.ssh/files and matched key set. It solves my challenges with user incidents setting up ssh. It may help you. https://github.com/BradleyA/docker-security-infrastructure/tree/master/ssh
Note: My previous answer (in Mar 2018) no longer works with the latest releases of openssh. Previous answer: diff -qs <(ssh-keygen -yf ~/.ssh/id_rsa) <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)
If you are in Windows and want use a GUI, with puttygen you can import your private key into it:
Once imported, you can save its public key and compare it to yours.
Just use puttygen and load your private key into it. It offers different options, e.g. exporting the corresponding public key.
Assuming you have the public keys inside X.509 certificates, and assuming they are RSA keys, then for each public key, do
openssl x509 -in certfile -modulus -noout
For each private key, do
openssl rsa -in keyfile -modulus -noout
Then match the keys by modulus.
Encrypt something with the public key, and see which private key decrypts it.
This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.