How to check if an RSA public / private key pair match
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.
PRIVKEY=id_rsa TESTKEY=id_rsa.pub diff <( ssh-keygen -y -e -f "$PRIVKEY" ) <( ssh-keygen -y -e -f "$TESTKEY" )
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 id_rsa.pub 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 id_rsa.pub
diff <(cut -d' ' -f 2 id_rsa.pub) <(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.
If they're on your local system, stick
id_rsa.pub in your
localhost using the
id_rsa key. If it works, then they match.
cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys ssh -i $HOME/.ssh/id_rsa localhost