How to check if an RSA public / private key pair match

Solution 1:

I would prefer the ssh-keygen -y -e -f <private key> way instead of the accepted answer of How do you test a public/private DSA keypair? on Stack Overflow.

ssh-keygen -y -e -f <private key> takes a private key and prints the corresponding public key which can be directly compared to your available public keys. (Hint: beware of comments or key-options.)

(How the hell is it doing that? I can only hope the public key is encoded directly or indirectly in the private key...)

I needed this myself and used the following Bash one-liner. It should output nothing if the keys belong together. Apply a little -q to the diff in scripts and diff only sets the return code appropriately.

diff <( ssh-keygen -y -e -f "$PRIVKEY" ) <( ssh-keygen -y -e -f "$TESTKEY" )

Solution 2:

Depending on where you get the public key file you are testing, the accepted answer may give false positive results. This is because of the behavior described in the comment by @drewbenn. Specifically, when the -e option is used with the private key file as the -f option parameter, it simply parrots (but reformats) what's in the associated public key file.

In other words,

ssh-keygen -y -f id_rsa

(apparently) generates the public key value, and

ssh-keygen -y -e -f id_rsa

simply and outputs (and reformats) the key in the existing whatever it is.

In my case, I have to verify that the pair has not been corrupted. So, I decided to compare the following:

ssh-keygen -y -f id_rsa | cut -d' ' -f 2


cut -d' ' -f 2


diff <(cut -d' ' -f 2 <(ssh-keygen -y -f id_rsa | cut -d' ' -f 2)

Perhaps this is not as flexible, but it is better for my needs. Maybe it helps someone else.

Solution 3:

If they're on your local system, stick in your $HOME/.ssh/authorized_keys and ssh to localhost using the id_rsa key. If it works, then they match.

cat $HOME/.ssh/ >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost