Cryptographic recipes and primitives for Python developers
npx @tessl/cli install tessl/pypi-cryptography@45.0.0A comprehensive Python cryptographic library providing cryptographic recipes and primitives to Python developers. The cryptography package serves as Python's cryptographic standard library, offering both high-level recipes for common cryptographic operations and low-level interfaces to cryptographic algorithms.
pip install cryptographypip install cryptography[ssh] for SSH key supportimport cryptography
from cryptography import __version__, __author__, __copyright__Common high-level imports:
from cryptography.fernet import Fernet, MultiFernet, InvalidToken
from cryptography import x509
from cryptography.exceptions import (
InvalidSignature, InvalidKey, UnsupportedAlgorithm,
AlreadyFinalized, InvalidTag
)Low-level hazmat imports (use with caution):
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.asymmetric import rsa, dsa, ec, padding
from cryptography.hazmat.primitives.kdf import pbkdf2, hkdffrom cryptography.fernet import Fernet
# Generate a key for symmetric encryption
key = Fernet.generate_key()
fernet = Fernet(key)
# Encrypt data
message = b"Secret message"
encrypted = fernet.encrypt(message)
# Decrypt data
decrypted = fernet.decrypt(encrypted)
print(decrypted) # b"Secret message"
# X.509 certificate handling
from cryptography import x509
from cryptography.hazmat.primitives import serialization
# Load a certificate from PEM data
cert = x509.load_pem_x509_certificate(pem_data)
print(cert.subject)
print(cert.public_key())The cryptography package follows a layered architecture separating safe high-level APIs from expert-level primitives:
This design ensures developers can use cryptography safely at the appropriate level for their expertise while maintaining access to full cryptographic functionality.
High-level symmetric encryption using authenticated encryption. Provides secure, simple encryption/decryption with built-in authentication and key rotation support.
class Fernet:
def __init__(self, key: bytes | str, backend: typing.Any = None): ...
@classmethod
def generate_key(cls) -> bytes: ...
def encrypt(self, data: bytes) -> bytes: ...
def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: ...
def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: ...
def decrypt_at_time(self, token: bytes | str, ttl: int, current_time: int) -> bytes: ...
def extract_timestamp(self, token: bytes | str) -> int: ...
class MultiFernet:
def __init__(self, fernets: Iterable[Fernet]): ...
def encrypt(self, msg: bytes) -> bytes: ...
def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes: ...
def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: ...
def decrypt_at_time(self, msg: bytes | str, ttl: int, current_time: int) -> bytes: ...
def rotate(self, msg: bytes | str) -> bytes: ...
def extract_timestamp(self, msg: bytes | str) -> int: ...
class InvalidToken(Exception): ...Comprehensive X.509 certificate handling including certificate creation, parsing, validation, and extension management. Supports certificate signing requests, certificate revocation lists, and certificate verification.
class Certificate:
def public_key(self): ...
def subject(self) -> Name: ...
def issuer(self) -> Name: ...
def serial_number(self) -> int: ...
class CertificateBuilder:
def subject_name(self, name: Name) -> 'CertificateBuilder': ...
def issuer_name(self, name: Name) -> 'CertificateBuilder': ...
def public_key(self, key) -> 'CertificateBuilder': ...
def sign(self, private_key, algorithm) -> Certificate: ...
def load_pem_x509_certificate(data: bytes) -> Certificate: ...
def load_der_x509_certificate(data: bytes) -> Certificate: ...Cryptographic hash functions including SHA family, SHA-3, BLAKE2, and more. Provides both one-shot hashing and incremental hash contexts.
class Hash:
def __init__(self, algorithm, backend=None): ...
def update(self, data: bytes) -> None: ...
def finalize(self) -> bytes: ...
class SHA256: ...
class SHA3_256: ...
class BLAKE2b:
def __init__(self, digest_size: int): ...Low-level symmetric encryption algorithms including AES, ChaCha20, and cipher modes. Provides building blocks for custom cryptographic protocols.
class Cipher:
def __init__(self, algorithm, mode, backend=None): ...
def encryptor(self) -> CipherContext: ...
def decryptor(self) -> CipherContext: ...
class AES:
def __init__(self, key: bytes): ...
class ChaCha20:
def __init__(self, key: bytes, nonce: bytes): ...Authenticated Encryption with Associated Data providing encryption and authentication in a single operation. Includes AES-GCM, ChaCha20-Poly1305, and other modern AEAD algorithms.
class AESGCM:
def __init__(self, key: bytes): ...
def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...
def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...
class ChaCha20Poly1305:
def __init__(self, key: bytes): ...
def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...
def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...Public-key cryptography including RSA, DSA, ECDSA, EdDSA, and key exchange algorithms. Supports key generation, digital signatures, and encryption.
def generate_private_key(public_exponent: int, key_size: int) -> RSAPrivateKey: ...
class RSAPrivateKey:
def public_key(self) -> RSAPublicKey: ...
def sign(self, data: bytes, padding, algorithm): ...
def private_bytes(self, encoding, format, encryption_algorithm): ...
class RSAPublicKey:
def verify(self, signature: bytes, data: bytes, padding, algorithm): ...
def encrypt(self, plaintext: bytes, padding): ...Password-based and key-based derivation functions for generating cryptographic keys from passwords or other key material. Includes PBKDF2, HKDF, Scrypt, and Argon2.
class PBKDF2HMAC:
def __init__(self, algorithm, length: int, salt: bytes, iterations: int): ...
def derive(self, key_material: bytes) -> bytes: ...
def verify(self, key_material: bytes, expected_key: bytes) -> None: ...
class HKDF:
def __init__(self, algorithm, length: int, salt: bytes = None, info: bytes = None): ...
def derive(self, key_material: bytes) -> bytes: ...Serialization and deserialization of cryptographic keys in various formats including PEM, DER, and SSH formats. Supports both public and private keys with optional encryption.
def load_pem_private_key(data: bytes, password: bytes = None) -> PrivateKey: ...
def load_pem_public_key(data: bytes) -> PublicKey: ...
def load_ssh_private_key(data: bytes, password: bytes = None) -> PrivateKey: ...
class Encoding:
PEM: Encoding
DER: Encoding
class PrivateFormat:
PKCS8: PrivateFormat
TraditionalOpenSSL: PrivateFormatMessage authentication codes and digital signatures for ensuring data integrity and authenticity. Includes HMAC, CMAC, and Poly1305.
class HMAC:
def __init__(self, key: bytes, algorithm): ...
def update(self, data: bytes) -> None: ...
def finalize(self) -> bytes: ...
def verify(self, signature: bytes) -> None: ...
class CMAC:
def __init__(self, key: bytes, algorithm): ...
def update(self, data: bytes) -> None: ...
def finalize(self) -> bytes: ...Time-based and HMAC-based one-time password (OTP) generation and verification for implementing two-factor authentication systems.
class TOTP:
def __init__(self, key: bytes, length: int, algorithm, time_step: int): ...
def generate(self, time: int) -> bytes: ...
def verify(self, totp: bytes, time: int) -> None: ...
class HOTP:
def __init__(self, key: bytes, length: int, algorithm): ...
def generate(self, counter: int) -> bytes: ...
def verify(self, hotp: bytes, counter: int) -> None: ...Additional utilities including constant-time operations and AES key wrapping functionality for secure key storage and timing attack prevention.
def bytes_eq(a: bytes, b: bytes) -> bool: ...
def aes_key_wrap(wrapping_key: bytes, key_to_wrap: bytes) -> bytes: ...
def aes_key_unwrap(wrapping_key: bytes, wrapped_key: bytes) -> bytes: ...
def aes_key_wrap_with_padding(wrapping_key: bytes, key_to_wrap: bytes) -> bytes: ...
def aes_key_unwrap_with_padding(wrapping_key: bytes, wrapped_key: bytes) -> bytes: ...Package-level metadata and version information:
__version__: str # "45.0.7"
__author__: str # "The Python Cryptographic Authority and individual contributors"
__copyright__: str # "Copyright 2013-2025 {__author__}"Common exceptions thrown by the cryptography library:
# Core exceptions from cryptography.exceptions
class UnsupportedAlgorithm(Exception):
def __init__(self, message: str, reason: _Reasons | None = None): ...
class InvalidSignature(Exception): ...
class InvalidKey(Exception): ...
class InvalidTag(Exception): ...
class AlreadyFinalized(Exception): ...
class AlreadyUpdated(Exception): ...
class NotYetFinalized(Exception): ...
class InternalError(Exception):
def __init__(self, msg: str, err_code: list[rust_openssl.OpenSSLError]): ...
# Fernet-specific exception
class InvalidToken(Exception): ... # from cryptography.fernetMost cryptographic operations can raise InvalidSignature, InvalidKey, or UnsupportedAlgorithm exceptions. Always handle these appropriately in production code.