Skip to content

Instantly share code, notes, and snippets.

@void-elf
Created January 27, 2017 23:30
Show Gist options
  • Select an option

  • Save void-elf/0ed0e136d6d342974257c93f571e28b5 to your computer and use it in GitHub Desktop.

Select an option

Save void-elf/0ed0e136d6d342974257c93f571e28b5 to your computer and use it in GitHub Desktop.
Verifying a certificate's signature matches the CA's public key using python-cryptography.
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
cert_file = open('/etc/letsencrypt/live/www.example.com/cert.pem')
cert_data = cert_file.read()
cert = x509.load_pem_x509_certificate(data=cert_data, backend=default_backend())
# chain contains the Let's Encrypt certificate
chain_file = open('/etc/letsencrypt/live/www.example.com/chain.pem')
chain_data = chain_file.read()
chain = x509.load_pem_x509_certificate(data=chain_data, backend=default_backend())
public_key = chain.public_key()
verifier = public_key.verifier(
signature = cert.signature,
padding = padding.PSS(
mgf = padding.MGF1(hashes.SHA256()),
salt_length = padding.PSS.MAX_LENGTH),
algorithm = hashes.SHA256())
verifier.update(cert.tbs_certificate_bytes)
verifier.verify()
# throws an InvalidSignature exception, but using verifying with openssl works.
@qtnull
Copy link

qtnull commented May 4, 2022

verifier = public_key.verifier(
                signature = cert.signature,
                padding = padding.PKCS1v15(),
                algorithm = hashes.SHA256()
)

Try changing the padding to padding.PKCS1v15(), it worked for me with self signed SSL certificates with openssl ca. Thanks to this StackOverflow comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment