Check if an SSL private key matches a certificate

{ openssl x509 -noout -modulus -in server.crt | openssl md5; openssl rsa -noout -modulus -in server.key | openssl md5; } | uniq

September 20, 2023but-i-am-dominator

Explanation

openssl x509 -noout -modulus -in server.crt uses the openssl tool to examine the file server.crt, which is a commonly used certificate file for secure communication. We print the "modulus" part from it.

openssl md5 uses the openssl tool again, this time to generate an MD5 hash (a type of checksum) from the standard input, piped from the previous command.

openssl rsa -noout -modulus -in server.key is similar to the first command, but this time we use it on the file server.key, which is a commonly used private key file for secure communication. As earlier, we print the modules part, and like earlier, we again use openssl md5 to generate an MD5 hash from that.

The two commands are in a grouping with { ...; }, so that we can pipe their combined output through uniq.

uniq filters out duplicate lines.

  • When the private key matches the certificate, both commands in the group will output the same line, so uniq will filter out and the second line, resulting in a single line of output.
  • When the private key and the certificate don't match, the two commands in the group will output different lines, so uniq will not filter out anything, resulting in 2 lines of output.