Compare a Key with its Certificate

Credit for this example goes to “Verifying that a Private Key Matches a Certificate” from the University of Wisconsin Knowledgebase.

To see if a key server.key belongs to the certificate server.crt, they need to have the same “modulus” and “exponent”.

openssl x509 -noout -text -in server.crt
openssl rsa -noout -text -in server.key

The exponent is quite always 65537. So we only need to compare the modulus.

openssl x509 -noout -modulus -in server.crt
openssl rsa -noout -modulus -in server.key

Example:

$ openssl x509 -noout -modulus -in server.cer 
Modulus=C8B04B9D50386C0B22296B181046712B83DB624DA4AA9B9CA78453DC78DA26D2295FDF79
A544CBF8013138FB0EDFD8F0CB13E2FBF8883263442AEA549450737360A2C4F607D2E4DADEA3E501
15DA6315BA3829A2F3E5D87293835D3F909234541F508FCFED435CCCD73880A6BCC488ABB8C6F3D8
0E55F5DC528AE325D007CC3489603668506BD77B555D0B5FAAFC671D96E36FEBE1250707E36B798B
5F993225311D3F2BB358BF382ECBBE4D87068AE2282F1FC3B7A382A6883871C9CD137683105D552C
5E4E19D9F6263D85697AC85B41C71F327F4E467DDA61E72053FDAD9594C71AC7F2B63AAC749D461C
7F4699C901C2F8987CC873703FC3932640354D63
$ openssl rsa -noout -modulus -in server.key 
Enter pass phrase for server.key:
Modulus=C8B04B9D50386C0B22296B181046712B83DB624DA4AA9B9CA78453DC78DA26D2295FDF79
A544CBF8013138FB0EDFD8F0CB13E2FBF8883263442AEA549450737360A2C4F607D2E4DADEA3E501
15DA6315BA3829A2F3E5D87293835D3F909234541F508FCFED435CCCD73880A6BCC488ABB8C6F3D8
0E55F5DC528AE325D007CC3489603668506BD77B555D0B5FAAFC671D96E36FEBE1250707E36B798B
5F993225311D3F2BB358BF382ECBBE4D87068AE2282F1FC3B7A382A6883871C9CD137683105D552C
5E4E19D9F6263D85697AC85B41C71F327F4E467DDA61E72053FDAD9594C71AC7F2B63AAC749D461C
7F4699C901C2F8987CC873703FC3932640354D63

It's easier to compare them if you calculate a MD5 sum:

openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5

Example:

$ openssl x509 -noout -modulus -in server.cer | openssl md5
(stdin)= 91cc0cf512b528689960a9fbd42bdabe
$ openssl rsa -noout -modulus -in server.key | openssl md5
Enter pass phrase for server.key:
(stdin)= 91cc0cf512b528689960a9fbd42bdabe