Customers regularly send me x509 key pairs at work1. Most of the time these have been forwarded a few times already, and people tend to mess up the files. This means that the public and private keys don't match anymore, and I have to ask for a new pair.
Luckily, we can use OpenSSL to check whether a public and private key match.
For RSA keys
The classic way to compare RSA keys is to check whether the modulus is the same, as this is the only part that is shared between the public and private keys. If the modulus isn't the same, the keys can't form a pair.
Read the modulus from the public key:
openssl rsa -pubin -in public.pem -modulus -noout | openssl sha1
Then do the same with the private RSA key:
openssl rsa -in private.pem -modulus -noout | openssl sha1
If the two values match, the key files form a pair.
Note that we're piping the actual output of the -modulus command to openssl sha1 to get a shorter hash of the modulus.
This makes it easier to manually compare the two values, but it's not strictly necessary.
You could also compare the output directly if you're feeling brave.
For EC keys
Elliptic curve keys don't have an easy-to-compare modulus like the RSA keys above had. However, it's always possible to generate the public key2 part when we have the private key.
Using the private key, generate (a hash of) the public key:
openssl pkey -pubout -in private.pem | openssl sha1
Then compare the output with the public key file you have.
We need to make openssl load it and print it out again to make sure we get the exact same format.
openssl x509 -pubkey -in public.pem -noout | openssl sha1
If the two values match, these keys form a pair.
-
Please don't do this. Ask the company that needs a certificate to generate a private key and provide you with a Certificate Signing Request (CSR). This way, you don't have to handle the private key at all. ↩
-
When people say "public key" in the context of a x509 pair they usually refer to the certificate. The public key we're extracting here is the actual cryptographic public key, it doesn't contain the extra data like domain names that a certificate usually holds. You can't recover the full certificate when you only have the private key. ↩