Danger
This is a “Hazardous Materials” module. You should ONLY use it if you’re 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns.
HPKE (Hybrid Public Key Encryption)
HPKE is a standard for public key encryption that combines a Key Encapsulation Mechanism (KEM), a Key Derivation Function (KDF), and an Authenticated Encryption with Associated Data (AEAD) scheme. It is defined in RFC 9180.
HPKE provides authenticated encryption: the recipient can be certain that the
message was encrypted by someone who knows the recipient’s public key, but
the sender is anonymous. Each call to Suite.encrypt() generates a fresh
ephemeral key pair, so encrypting the same plaintext twice will produce
different ciphertext.
The info parameter should be used to bind the encryption to a specific
context (e.g., “MyApp-v1-UserMessages”). Per RFC 9180 Section 8.1,
applications using single-shot APIs should use the info parameter for
specifying auxiliary authenticated information.
from cryptography.hazmat.primitives.hpke import Suite, KEM, KDF, AEAD
from cryptography.hazmat.primitives.asymmetric import x25519
suite = Suite(KEM.X25519, KDF.HKDF_SHA256, AEAD.AES_128_GCM)
# Generate recipient key pair
private_key = x25519.X25519PrivateKey.generate()
public_key = private_key.public_key()
# Encrypt
ciphertext = suite.encrypt(b"secret message", public_key, info=b"app info")
# Decrypt
plaintext = suite.decrypt(ciphertext, private_key, info=b"app info")
- class cryptography.hazmat.primitives.hpke.Suite(kem, kdf, aead)
An HPKE cipher suite combining a KEM, KDF, and AEAD.
- Parameters:
- encrypt(plaintext, public_key, info=b'')
Encrypt a message using HPKE.
- Parameters:
plaintext (bytes) – The message to encrypt.
public_key (
X25519PublicKey) – The recipient’s public key.info (bytes) – Application-specific context string for binding the encryption to a specific application or protocol.
- Returns:
The encapsulated key concatenated with ciphertext (enc || ct).
- Return type:
- decrypt(ciphertext, private_key, info=b'')
Decrypt a message using HPKE.
- Parameters:
private_key (
X25519PrivateKey) – The recipient’s private key.info (bytes) – Application-specific context string (must match the value used during encryption).
- Returns:
The decrypted plaintext.
- Return type:
- Raises:
cryptography.exceptions.InvalidTag – If decryption fails.
- class cryptography.hazmat.primitives.hpke.KEM
An enumeration of key encapsulation mechanisms.
- X25519
DHKEM(X25519, HKDF-SHA256)
- P256
DHKEM(P-256, HKDF-SHA256)
- P384
DHKEM(P-384, HKDF-SHA384)
- P521
DHKEM(P-521, HKDF-SHA512)