SSL Certificate Private Key Validation

PUBLISHED ON MAY 26, 2026 — HOW-TO, PYTHON, SSL

I had an issue the other day with an SSL Certificate and Private Key that didn’t match. Here is how I validated it.

First, ensure you have the cryptography library installed.

pip install cryptography

Then, use the following script to validate the SSL Certificate and Private Key.

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.x509 import load_pem_x509_certificate

# Load private key
with open("your-private.key", "rb") as key_file:
    private_key = serialization.load_pem_private_key(key_file.read(), password=None)

# Load certificate
with open("your-certificate.pem", "rb") as cert_file:
    cert = load_pem_x509_certificate(cert_file.read())

# Get the public key from the certificate
public_key = cert.public_key()

# Check if the public key matches the private key
if isinstance(public_key, rsa.RSAPublicKey) and isinstance(private_key, rsa.RSAPrivateKey):
    if private_key.public_key().public_numbers() == public_key.public_numbers():
        print("The private key belongs to the certificate.")
    else:
        print("The private key does NOT belong to the certificate.")

I ran this script, and it told me that the private key did not belong to the certificate. So I knew I had the wrong private key. This saved me a lot of time troubleshooting.

comments powered by Disqus