std/hpke
import std/hpke to use it. Source: src/std/hpke.iyi at v0.22.0.
import std/hpke::{HpkeSuite, HpkeKem, HpkeKdf, HpkeAead, HpkePrivateKey, HpkePublicKey, HpkeError} suite = HpkeSuite.new(HpkeKem::X25519Sha256, HpkeKdf::HkdfSha256, HpkeAead::Aes128Gcm)
key = HpkePrivateKey.derive(suite.kem, ikm) # DeriveKeyPair, section 7.1.3
key.public_key.bytes # SerializePublicKey: 32 bytes, sent
theirs = HpkePublicKey.from_bytes(suite.kem, bytes).or_panic # read back, checked
enc, sealed = suite.seal(theirs, info, aad, plaintext, randomness).or_panic
suite.open(key, enc, info, aad, sealed) # the plaintext, or an HpkeError sender = suite.sender(theirs, info, randomness).or_panic # a context: enc, then messages
sender.enc
sender.seal(plaintext, aad) # sequence 0, 1, 2, ...
recipient = suite.recipient(key, sender.enc, info).or_panic
recipient.open(sealed, aad)
sender.export(exporter_context, 32) # section 5.3, both ends alikeAll four modes: psk: and psk_id: given make it mode_psk, sender_key: (the sender's static key, at the sender) and sender_public: (its public half, at the recipient) mode_auth, and both mode_auth_psk; neither is mode_base. The suites are any of three KEMs, DHKEM(X25519, HKDF-SHA256) 0x0020, DHKEM(P-256, HKDF-SHA256) 0x0010 and DHKEM(P-384, HKDF-SHA384) 0x0011; three KDFs, HKDF-SHA256, -SHA384 and -SHA512; and four AEADs, AES-128-GCM, AES-256-GCM, ChaCha20-Poly1305 and the export-only 0xFFFF, whose context exports secrets and seals nothing. HpkeSuite.from_ids reads a suite named by its three code points, as ECH's configurations and OHTTP's key configurations carry them, and answers an HpkeError for one this module does not have. Single-shot seal, open, send_export and receive_export are section 6's; the KEM itself is there as HpkeKem#encapsulate and #decapsulate (section 4.1).
Not here: DHKEM(P-521) and DHKEM(X448), for want of the curves in std; and the post-quantum KEMs, ML-KEM-768 (0x0041) and X25519 with ML-KEM-768 (X-Wing, 0x647A). IANA's registry lists both, but against Internet-Drafts (draft-connolly-cfrg-hpke-mlkem and draft-connolly-cfrg-xwing-kem), and draft-ietf-hpke-pq-05, in IESG evaluation when this was written (2026-10-22), asks IANA to replace the 0x647A entry and derives both KEMs' keys with a SHAKE256 LabeledDerive that only the revision of RFC 9180 (draft-ietf-hpke-hpke), itself a draft, defines: neither the code points' meaning nor their test vectors had settled.
Keys, randomness, info, aad, psk and messages are a String, whose bytes are taken, or an Array(UInt8). What is sealed and opened comes back a String, as std/aead answers it, so a message is not copied again; keys, encapsulations and exported secrets come back an Array(UInt8). The caller brings every random byte, as std/curve25519's and std/mlkem's do: an encapsulation's ephemeral key is DeriveKeyPair(randomness), which is the RFC's GenerateKeyPair given at least Nsk random bytes (32, or 48 for P-384) from Random::Secure.random_bytes. Nothing here draws a number or reads a clock; but std/p256 and std/p384 import std/asn1 (for their PKCS #8 and SEC 1 keys), which imports std/time, so iyi mod reach counts std/time and std/env among what a package using this one reaches, which std/aead and std/curve25519 alone do not.
Serialisation is section 7.1.1's: an X25519 key is its 32 bytes, a P-256 or P-384 public key the uncompressed point, 0x04 then x and y, 65 or 97 bytes, and a private key the scalar, 32 or 48 bytes big-endian. An X25519 private key is clamped when it is serialised (section 7.1.2): it is the same key, and RFC 9180's vectors print it unclamped, as DeriveKeyPair made it. A P-256 or P-384 public key is validated when it is read, as section 7.1.4 asks (on the curve, coordinates below p; the uncompressed form cannot spell the point at infinity), and so is every encapsulation.
Answered as an HpkeError, a value, because the bytes come from outside: an encapsulation or a public key of the wrong length; a P-256 or P-384 point not on its curve; an X25519 shared secret of all zero bytes (the peer's key is of small order, section 7.1.4, which std/curve25519 refuses and this passes on); a ciphertext whose tag does not match, including one opened at the wrong sequence number, under the wrong info, psk, psk_id or sender key; a context sealing or opening past its last nonce (sequence 2^96 - 1, which section 5.2's IncrementSeq refuses to step past, so the last message is sequence 2^96 - 2); and a suite named by code points this module does not have. A failed open leaves the sequence where it was, as the RFC's ContextR.Open does.
Refused with a sentence, as the caller's own misuse: a key of one KEM given to a suite of another; input keying material or randomness shorter than Nsk (section 7.1.3 says it SHOULD be at least that); a psk shorter than 32 bytes (section 5.1.2: it MUST have 32 bytes of entropy); a psk without a psk_id or a psk_id without a psk (section 5.1's VerifyPSKInputs); an export longer than 255 hashes; and seal or open on an export-only context. DeriveKeyPair failing, which for P-256 takes 256 candidates in a row at or above the group order, each a chance under 2^-32, is a panic, as section 8.2 allows.
Constant time on secrets. Nothing this module adds branches on a secret or indexes memory by one: the labeled HKDF steps are std/crypto's HMAC, the AEADs std/aead's bitsliced AES-GCM and ChaCha20-Poly1305 (tags compared by OR-ing the differences), and the Diffie-Hellman steps std/curve25519's ladder and std/p256's and std/p384's fixed-window multiplications, each constant-time as its own header says and measures. The nonce is the base nonce XORed with the sequence number, which is public. What does branch on a secret is RFC 9180's own: DeriveKeyPair's rejection of a P-256 or P-384 candidate at or above the order (the branch says a candidate was refused, and nothing of the one kept), and the all-zero check on an X25519 secret, which depends on the peer's key.
Measured on one x86_64 Linux machine other jobs shared, --release, the best of five runs of 200 (bench/std_hpke_exercise.sh), X25519, HKDF-SHA256 and AES-128-GCM over a 1 KiB message: a single-shot seal took 46 microseconds and a single-shot open 36; in an established context, a seal took 3.8 and an open 5.0. The curve is most of the single-shot time: seal makes the ephemeral key (a fixed-base multiplication, 9 microseconds) and both do an X25519 ladder (21), and the labeled HKDF steps, eight HMACs to open and ten to seal, take under a microsecond each.
Held by bench/std_hpke_exercise.sh to RFC 9180's test vectors (Appendix A, from the CFRG's test-vectors.json) for every suite of them this module has - DHKEM(X25519) and DHKEM(P-256), with HKDF-SHA256 and HKDF-SHA512, each AEAD, each mode: the key pairs from their ikm, the encapsulation and shared secret, every encryption of the 257 at the sender and the recipient, the key and base nonce at sequence 2^96 - 2, and the exports - and to an HPKE written in Python over the primitives of Python's cryptography (its X25519, P-256, P-384, HMAC and AEADs), the same bytes from the same randomness and each opening what the other sealed, in all 36 suites and all four modes; and by broken copies of this module and of std/curve25519, each caught at the check that names it. The RFC has no vectors for DHKEM(P-384) or HKDF-SHA384; the Python HPKE is what holds those, after it has passed the RFC's vectors itself.
What this is not: a way to keep a key out of memory. Private keys, shared secrets and context keys live in the collected heap, and nothing wipes them.
HpkeAeadenum
The AEADs, by their code points (section 7.3, table 5).
pub enum HpkeAead : Int32
Aes128Gcm = 1
Aes256Gcm = 2
ChaCha20Poly1305 = 3
ExportOnly = 65535
# Nk: the bytes of a key; none for export-only.
def key_size : Int32
def name : String
# Nn: the bytes of a nonce; none for export-only.
def nonce_size : Int32
# Nt: the bytes of a tag; none for export-only.
def tag_size : Int32
endHpkeErrorstruct
What is wrong with an encapsulation, a key, a ciphertext or a suite from outside, or a context out of nonces: message is the sentence.
pub struct HpkeError
def initialize(message : String)
def to_s : String
endHpkeKdfenum
The KDFs, by their code points (section 7.2, table 3).
pub enum HpkeKdf : Int32
HkdfSha256 = 1
HkdfSha384 = 2
HkdfSha512 = 3
# HKDF-Expand (RFC 5869 section 2.3) of *prk* to *length* bytes.
def expand(prk : Array(UInt8), info : Array(UInt8), length : Int32) : Array(UInt8)
# Nh: the bytes of the hash's output.
def hash_size : Int32
# HMAC under the hash, keyed with *key*.
def mac(key : String | Array(UInt8)) : HMAC
def name : String
endHpkeKemenum
The KEMs, by their code points (section 7.1, table 2).
pub enum HpkeKem : Int32
P256Sha256 = 16
P384Sha384 = 17
X25519Sha256 = 32
# Decap, or AuthDecap when *sender_public* is given (section 4.1): the
# shared secret *enc* carries to *key*, or an `HpkeError` for an *enc*
# of the wrong length, not a point of the curve, or of small order.
def decapsulate(key : HpkePrivateKey, enc : String | Array(UInt8), sender_public : HpkePublicKey | Nil = nil) : Array(UInt8) | HpkeError
# Encap, or AuthEncap when *sender_key* is given (section 4.1): the
# encapsulation, enc, and the shared secret, from the ephemeral key
# DeriveKeyPair makes of *randomness* (at least Nsk bytes). An
# `HpkeError` when a Diffie-Hellman step is refused: *recipient* is an
# X25519 key of small order.
def encapsulate(recipient : HpkePublicKey, randomness : String | Array(UInt8), sender_key : HpkePrivateKey | Nil = nil) : ::Tuple(Array(UInt8), Array(UInt8)) | HpkeError
# The KDF the KEM's own steps use (section 4.1), whatever the suite's.
def kdf : HpkeKdf
# RFC 9180's name for it.
def name : String
# Nsk: the bytes of a serialised private key.
def private_key_size : Int32
# Nenc and Npk, which are the same: a serialised public key.
def public_key_size : Int32
# Nsecret: the bytes of a shared secret, the KEM's hash's.
def secret_size : Int32
endHpkeModeenum
The four modes of section 5, by the byte the key schedule binds.
pub enum HpkeMode : Int32
Base = 0
Psk = 1
Auth = 2
AuthPsk = 3
endHpkePrivateKeystruct
A KEM's private key and the public key that goes with it.
pub struct HpkePrivateKey
# DH(sk, pk) of section 4.1 with the serialised public key *peer*: the
# X25519 secret, or the x-coordinate of the product on P-256 and P-384.
# An `HpkeError` for a peer of the wrong length, a point not on the
# curve, or an all-zero X25519 secret (section 7.1.4).
def agree(peer : String | Array(UInt8)) : Array(UInt8) | HpkeError
# SerializePrivateKey: the 32 bytes of an X25519 key, clamped; the
# scalar of a P-256 or P-384 key, 32 or 48 bytes big-endian.
def bytes : Array(UInt8)
# DeriveKeyPair (section 7.1.3): the key pair of *ikm*, at least Nsk
# bytes, under the KEM's own KDF. For P-256 and P-384, candidates are
# drawn until one is in [1, n - 1].
def self.derive(kem : HpkeKem, ikm : String | Array(UInt8)) : HpkePrivateKey
# DeserializePrivateKey: the key *bytes* are, or an `HpkeError` for the
# wrong length or, on P-256 and P-384, a scalar not in [1, n - 1]. An
# X25519 key is clamped (section 7.1.2).
def self.from_bytes(kem : HpkeKem, bytes : String | Array(UInt8)) : HpkePrivateKey | HpkeError
def initialize(kem : HpkeKem, public_key : HpkePublicKey, secret : Array(UInt8), curve : P256PrivateKey | P384PrivateKey | Nil)
def kem : HpkeKem
def public_key : HpkePublicKey
endHpkePublicKeystruct
A KEM's public key, serialised as section 7.1.1 has it.
pub struct HpkePublicKey
# SerializePublicKey: 32 bytes for X25519, the uncompressed point for
# P-256 (65) and P-384 (97).
def bytes : Array(UInt8)
# DeserializePublicKey, validated: the key *bytes* are, or an
# `HpkeError` for the wrong length or a point not on the curve.
def self.from_bytes(kem : HpkeKem, bytes : String | Array(UInt8)) : HpkePublicKey | HpkeError
def initialize(kem : HpkeKem, bytes : Array(UInt8))
def kem : HpkeKem
endHpkeRecipientclass
The recipient's context (section 5.2): messages opened at sequence 0, 1, 2 and on, and secrets exported, the same ones the sender's exports.
pub class HpkeRecipient
# Skips the sequence forward to *sequence*, never back: a message lost
# in between is not opened.
def advance_to(sequence : UInt128) : Nil
# Context.Export (section 5.3).
def export(exporter_context : String | Array(UInt8), length : Int32) : Array(UInt8)
def initialize(cipher : HpkeCipher)
# The mode the context was set up in, by the inputs given.
def mode : HpkeMode
# ContextR.Open: the plaintext of *ciphertext* at the next nonce, or an
# `HpkeError` - its tag does not match, or the sequence is at 2^96 - 1 -
# with the sequence left where it was.
def open(ciphertext : String | Array(UInt8), aad : String | Array(UInt8) = "") : String | HpkeError
# The sequence number the next message is opened at.
def sequence : UInt128
endHpkeSenderclass
The sender's context (section 5.2): enc for the recipient, then messages sealed at sequence 0, 1, 2 and on, and secrets exported.
pub class HpkeSender
# Skips the sequence forward to *sequence*, never back, so no nonce is
# used twice: for a protocol that numbers its messages itself.
def advance_to(sequence : UInt128) : Nil
# The encapsulation the recipient sets its context up from.
def enc : Array(UInt8)
# Context.Export (section 5.3): *length* bytes, at most 255 hashes,
# bound to *exporter_context*.
def export(exporter_context : String | Array(UInt8), length : Int32) : Array(UInt8)
def initialize(enc : Array(UInt8), cipher : HpkeCipher)
# The mode the context was set up in, by the inputs given.
def mode : HpkeMode
# ContextS.Seal: *plaintext* sealed under the next nonce, *aad*
# authenticated with it; or an `HpkeError` once the sequence is at
# 2^96 - 1, with nothing sealed.
def seal(plaintext : String | Array(UInt8), aad : String | Array(UInt8) = "") : String | HpkeError
# The sequence number the next message is sealed at.
def sequence : UInt128
endHpkeSuitestruct
A KEM, a KDF and an AEAD: what the two ends agree on before anything is sealed, and what every function of sections 5 and 6 runs under.
pub struct HpkeSuite
def aead : HpkeAead
# The suite named by its three code points, or an `HpkeError` naming the
# one this module does not have.
def self.from_ids(kem_id : Int32, kdf_id : Int32, aead_id : Int32) : HpkeSuite | HpkeError
def initialize(kem : HpkeKem, kdf : HpkeKdf, aead : HpkeAead)
def kdf : HpkeKdf
def kem : HpkeKem
# Single-shot Open<MODE> (section 6.1): the plaintext, or an `HpkeError`.
def open(key : HpkePrivateKey, enc : String | Array(UInt8), info : String | Array(UInt8), aad : String | Array(UInt8), ciphertext : String | Array(UInt8), psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_public : HpkePublicKey | Nil = nil) : String | HpkeError
# Single-shot ReceiveExport<MODE> (section 6.2): what `send_export`
# exported, or an `HpkeError` when *enc* is refused.
def receive_export(key : HpkePrivateKey, enc : String | Array(UInt8), info : String | Array(UInt8), exporter_context : String | Array(UInt8), length : Int32, psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_public : HpkePublicKey | Nil = nil) : Array(UInt8) | HpkeError
# SetupBaseR, SetupPSKR, SetupAuthR or SetupAuthPSKR (section 5.1): the
# recipient's context for *enc*, or an `HpkeError` when *enc* is refused.
# The mode is chosen as `sender`'s is, by *sender_public* in place of
# the sender's key.
def recipient(key : HpkePrivateKey, enc : String | Array(UInt8), info : String | Array(UInt8), psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_public : HpkePublicKey | Nil = nil) : HpkeRecipient | HpkeError
# Single-shot Seal<MODE> (section 6.1): enc and *plaintext* sealed, the
# context's first message.
def seal(recipient : HpkePublicKey, info : String | Array(UInt8), aad : String | Array(UInt8), plaintext : String | Array(UInt8), randomness : String | Array(UInt8), psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_key : HpkePrivateKey | Nil = nil) : ::Tuple(Array(UInt8), String) | HpkeError
# Single-shot SendExport<MODE> (section 6.2): enc and *length* bytes
# exported under *exporter_context*.
def send_export(recipient : HpkePublicKey, info : String | Array(UInt8), exporter_context : String | Array(UInt8), length : Int32, randomness : String | Array(UInt8), psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_key : HpkePrivateKey | Nil = nil) : ::Tuple(Array(UInt8), Array(UInt8)) | HpkeError
# SetupBaseS, SetupPSKS, SetupAuthS or SetupAuthPSKS (section 5.1), by
# which of *psk* and *psk_id*, and *sender_key*, are given: the sender's
# context, whose `enc` goes to the recipient. An `HpkeError` when the
# encapsulation is refused (*recipient* is an X25519 key of small order).
def sender(recipient : HpkePublicKey, info : String | Array(UInt8), randomness : String | Array(UInt8), psk : String | Array(UInt8) | Nil = nil, psk_id : String | Array(UInt8) | Nil = nil, sender_key : HpkePrivateKey | Nil = nil) : HpkeSender | HpkeError
def to_s : String
endError for HpkeErrorimpl
impl Error for HpkeError
def message : String
end
Hybrid Public Key Encryption (RFC 9180), written in iyi over std/curve25519, std/p256, std/p384, std/crypto's HMAC and std/aead: what TLS Encrypted Client Hello and Oblivious HTTP seal their messages with.