Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Cryptography: Certificates and Hashes

Learn how to hash data with hashlib, load and inspect X.509 certificates, verify certificate chains, and use certificate keys to sign and verify messages in Python.

~4 min readPython
#cryptography#certificates#hashing#x509
A visual metaphor showing a padlock and a certificate chain, representing Python cryptography for certificates and hashes.

Python's standard library and the cryptography package provide practical tools for hashing data and validating X.509 certificates. This article shows how to compute digests with hashlib, load and inspect certificates, verify a certificate chain, and use the private key associated with a certificate to sign and verify messages.

Hashing Data with hashlib

The hashlib module in the standard library provides a uniform interface for cryptographic hash functions. The most common use is computing a digest of a message to detect accidental or malicious changes.

python
import hashlib message = b"critical configuration data" digest = hashlib.sha256(message).hexdigest() print(digest)

The sha256 function returns a hash object, and calling hexdigest() produces a hexadecimal string. The same message always produces the same digest, and a change in the input produces a completely different digest. This property is what makes hashes useful for integrity checks.

For large data, you can update the hash incrementally instead of loading the entire input into memory:

python
h = hashlib.sha256() with open("large_file.bin", "rb") as f: for chunk in iter(lambda: f.read(4096), b""): h.update(chunk) print(h.hexdigest())

hashlib supports several algorithms, including sha256, sha384, sha512, and the older sha1 and md5. For security-sensitive applications, prefer SHA-256 or stronger. MD5 and SHA-1 are considered broken for collision resistance and should only be used for compatibility with legacy systems.

Loading and Inspecting X.509 Certificates

The cryptography library provides an X.509 implementation. You typically load a certificate from PEM or DER format and then inspect its fields.

python
from cryptography import x509 from cryptography.hazmat.backends import default_backend with open("server.crt", "rb") as f: cert = x509.load_pem_x509_certificate(f.read(), default_backend()) print(cert.subject) print(cert.issuer) print(cert.not_valid_before) print(cert.not_valid_after)

The subject and issuer are Name objects containing attributes like CN (common name) and O (organization). You can access them directly:

python
common_name = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) print(common_name[0].value)

The certificate also holds the public key, which you can extract for verification or encryption:

python
public_key = cert.public_key()

This key is used later to verify signatures or establish TLS sessions.

Verifying Certificate Chains

A certificate alone is not proof of identity. It must be signed by a trusted authority, and the chain from the leaf certificate up to a root must be valid. The basic cryptography APIs do not automatically verify an entire chain. Some recent cryptography releases include an x509.verification module; if your installed version has it, prefer that for production. Otherwise, you can build minimal verification logic yourself and use a trust store such as certifi for root certificates.

A minimal chain check involves confirming that each certificate is signed by the next one in the chain and that the root is in your trust store. The verify_directly_issued_by method checks the signature:

python
def verify_chain(leaf, intermediates, roots): current = leaf while current.issuer != current.subject: issuer = next(c for c in intermediates + roots if c.subject == current.issuer) current.verify_directly_issued_by(issuer) current = issuer return current in roots

This is simplified. Real verification must also check validity dates, key usage extensions, and hostname matching, and it must define what happens when no matching issuer is found. verify_directly_issued_by checks signatures but does not enforce policy constraints. For production, use cryptography's x509.verification module if available, or a dedicated TLS library.

Signing and Verifying Messages with Certificates

The private key corresponding to a certificate signs data, and the certificate's public key verifies the signature. In the example, private_key.sign hashes the message internally using the provided hash algorithm, so you do not need to hash it manually before calling sign.

python
from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_private_key # Load private key with open("private_key.pem", "rb") as f: private_key = load_pem_private_key(f.read(), password=b"passphrase") message = b"important message" signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() )

To verify, use the public key extracted from the certificate:

python
public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() )

The padding parameters must match between signing and verification. PSS is recommended for modern systems; PKCS1v15 is still used for compatibility but has stricter requirements.

Common Pitfalls in Certificate and Hash Handling

Several mistakes recur when working with certificates and hashes in Python. One is mixing up binary and text encodings. Hashes and signatures are bytes; converting them to strings incorrectly can corrupt data. Always use b prefixes for byte literals and decode only when necessary.

Another pitfall is ignoring certificate validity dates. A certificate can be expired or not yet valid. The cryptography library does not automatically check these; you must compare not_valid_before and not_valid_after against the current time.

Hostname verification is another frequent gap. When a certificate is presented for a TLS connection, the certificate's subject or SAN must match the hostname. The cryptography library does not perform this check for you; you need to implement it or rely on higher-level libraries like requests or ssl.

Finally, hash algorithm confusion can break signatures. The hash algorithm used in the signature must match the one used when verifying. If you change the algorithm, all existing signatures become invalid.

Security Considerations for Production Systems

When deploying code that handles certificates and hashes, the way you manage keys matters more than the cryptographic primitives. Private keys should be stored in secure hardware or a key management service, not in plaintext files. If a private key is compromised, the entire certificate chain is meaningless.

Hash algorithms should be chosen based on current recommendations. SHA-256 is a baseline, but SHA-384 or SHA-512 may be appropriate for higher security levels. Avoid rolling your own cryptographic protocols; use established libraries and patterns.

Certificate revocation and renewal are operational concerns. A certificate that is compromised must be revoked, and your code should check revocation status if possible. However, OCSP and CRL checks add complexity and may not be available in all environments. Consider whether your threat model requires them.

Finally, keep the cryptography library updated. Cryptographic vulnerabilities are discovered over time, and patching libraries is a critical part of maintaining security. The same applies to the underlying OpenSSL or other backends that cryptography uses.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.