views:

1129

answers:

7

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 which go with which.

Again, these are pub/key files, DSA.

I would really prefer a one-liner of some sort...

+2  A: 

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 crypto 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.

Mitch Wheat
I'm looking for something a bit more simple. Say, a shell one liner or the like. I'm on linux, and have the normal stuff such as openssl installed.
Lokkju
A: 

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.

Martin v. Löwis
A: 

Will matching certificates not have matching thumbprints? You can get the thumbprint with something like

openssl x509 -in cert.pem -noout -fingerprint
Andrew Cox
as I said, these are not x509/pem files, these are key/pub files.
Lokkju
A: 

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.

Martin v. Löwis
+2  A: 

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.

Lokkju
+2  A: 

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.

Bill the Lizard
+1  A: 

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.

Robert