1.2.7 Verifying That Certificate Matches a Private Key
A common mistake when deploying certificates is to use a wrong private key. This happens more often than you might think. For example, if you’re manually updating the certificate on your server, you might end up configuring your new certificate alongside your old private key. You’d probably prefer to find this out before you restart your web server and cause some downtime.
The check consists of extracting the public key from the certificate:
$ openssl x509 -in cert.pem -noout -pubkey
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApeYU4jNfL6P97JXZ3Lqg
5Dn+DMC7RzUpBybCCRKK7HJBmt4PspRKTlfe3qKBethJyHqk5ZgZDKwfDh43VeSL
yj+jzk7YdIQONQBF7tZIK3G0cgRhAaUV1ZgYHbmrtdd1Wcj3TrKchrPgC0ymtTDK
+RV0I6mzdG2ssZDsyHlhobSL2rdaJQmctn0dOZ5PRxYm4E1mumJXfXRwCKaQFJh9
9FUSF0dbT0/gIJ36wpzIEyB5FuXXnyit0+JP/DB2VOK+2NLo1w+793Myln4diZy2
ADxmvc8OmROyWHdb3nI9v4y7ADUfnH7BtjJbROxjTbCCzdDiiADqHt4Y0dVcrTHH
NQIDAQAB
-----END PUBLIC KEY-----
Actually, you’ll probably only want to compare the public keys, so it’s probably simpler to aim to produce a hash of the output straight away:
$ openssl x509 -in cert.pem -noout -pubkey | sha256sum
6385044bd69e6c73b145a66e8a8f9ab6ec9dd00d6fd06ab85f09725f05ce050f -
In the second step, we look at the private key to generate its corresponding public key, and hash that:
$ openssl pkey -in privkey.pem -pubout | sha256sum
6385044bd69e6c73b145a66e8a8f9ab6ec9dd00d6fd06ab85f09725f05ce050f -
If the hashes are the same, then you know that the certificate and private key belong together.