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" )

Leave a Comment