How to Use OpenSSL to Check if TLS Private Key and TLS Certificate Form a Matching Pair
The aim of this page📝 is to explain how to validate and match a DSA/RSA encrypted private key with a certificate.
2 min readOct 30, 2023
- A private key and a certificate form a pair that is used for secure communication.
- The private key is kept secret and is used to sign digital messages.
- The certificate contains the public key and is shared publicly.
- Public key can be used to verify the digital signatures created with the private key.
- It’s crucial that the private key matches the certificate — If they don’t match, secure communication won’t be possible.
- A DSA private key can be in traditional format or PKCS#8 format.
- The type of the private key (RSA, DSA, EC) can be determined by examining the header of the key file or by using OpenSSL commands.
- The latter is a standard format that can include any type of key and provides more features, such as password protection.
- To view the details of a DSA private key, you can use
openssl dsa -in privateKey.pem -text
. - To ensure that a DSA private key matches a certificate, you can compare the public keys derived from both. I
- If they are identical, it means they form a matching pair.
CODE
Here is a particular example I have experienced:
# Extract public key from private key
openssl dsa -in privateKey.pem -pubout -out pubkey.pem
# OR
openssl rsa -in privateKey.pem -pubout -out pubkey.pem
# Extract public key from certificate
openssl x509 -pubkey -noout -in cert.pem > certpubkey.pem
# Compare public keys in Powershell
▶ diff (cat .\remrem_pubkey.pem) (cat .\remrem_certpubkey.pem)
# Compare public keys in Bash
diff pubkey.pem certpubkey.pem
- In the example above, replace
privateKey.pem
,pubkey.pem
,cert.pem
, andcertpubkey.pem
with your actual file names. - No output of the
diff
command means that the files are fully identical and therefore the certificate and private match indeed form a pair