cryptography

46.0.6 · active · verified Fri Mar 27

The cryptography library (pyca/cryptography) provides cryptographic recipes and primitives to Python developers, aiming to be a 'cryptographic standard library'. It offers both high-level recipes (e.g., Fernet symmetric encryption) and low-level hazmat (hazardous materials) primitives covering symmetric ciphers, asymmetric algorithms (RSA, EC, DSA), message digests, KDFs, X.509, and more. Current stable version is 46.0.6 (released 2026-03-25). The project releases frequently—typically multiple times per major version cycle—with major versions arriving several times per year.

Warnings

Install

Imports

Quickstart

Fernet high-level symmetric encryption (recommended starting point) plus AES-GCM via hazmat for authenticated low-level encryption.

# --- High-level: Fernet (recommended for most use cases) ---
from cryptography.fernet import Fernet

key = Fernet.generate_key()          # Must be stored securely; bytes
f = Fernet(key)
token = f.encrypt(b"secret message")  # Returns URL-safe base64 token
plaintext = f.decrypt(token)          # Raises InvalidToken if tampered
assert plaintext == b"secret message"

# --- Low-level: AES-GCM via hazmat (authenticated encryption) ---
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

aes_key = AESGCM.generate_key(bit_length=256)  # 32 random bytes
aesgcm = AESGCM(aes_key)
nonce = os.urandom(12)               # 96-bit nonce; NEVER reuse with same key
ciphertext = aesgcm.encrypt(nonce, b"secret data", b"optional AAD")
decrypted = aesgcm.decrypt(nonce, ciphertext, b"optional AAD")
assert decrypted == b"secret data"

# --- RSA key generation & sign/verify ---
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
message = b"message to sign"
signature = private_key.sign(
    message,
    padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
    hashes.SHA256()
)
public_key.verify(
    signature, message,
    padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
    hashes.SHA256()
)  # Raises InvalidSignature if verification fails
print("All operations succeeded")

view raw JSON →