HKDF
Extract-then-expand key derivation used to turn shared secrets into session keys, in TLS 1.3, Signal and most hybrid KEM combiners.
Why it's safe
HKDF with SHA-256 or SHA-384 is safe against known quantum attacks. It is the usual tool for combining a classical and a post-quantum shared secret into one key.
- Used for
- Key derivation
- Family
- Key derivation (HMAC-based)
- Standards
- RFC 5869, NIST SP 800-56C Rev. 2
Migration guides
How to adopt HKDF. Pick your stack.
Go crypto/mlkem (1.24+), crypto/mldsa (1.27+) · goGo: application-level ML-KEM (crypto/mlkem) and ML-DSA (crypto/mldsa) in the standard libraryProduction-ready
Why
Go ships post-quantum primitives in the standard library: crypto/mlkem (ML-KEM-768 and ML-KEM-1024, FIPS 203) since Go 1.24, and crypto/mldsa (ML-DSA-44/65/87, FIPS 204) since Go 1.27, which also taught crypto/x509 and crypto/tls about ML-DSA. Go 1.24 also added crypto/hkdf, which you need to turn shared secrets into keys. Go 1.26 added crypto/hpke with post-quantum hybrid KEMs, which is the best choice if you need public-key encryption of messages.
Steps
- Upgrade the toolchain (
go 1.24for ML-KEM,go 1.27for ML-DSA ingo.mod). - Replace RSA-OAEP / ECDH key wrapping with ML-KEM (ideally hybrid with X25519, or use
crypto/hpke). - Replace ECDSA/Ed25519 signing with ML-DSA where verifiers can be upgraded; keep an algorithm identifier with every signature.
Before
priv, _ := ecdh.X25519().GenerateKey(rand.Reader)
peer, _ := ecdh.X25519().GenerateKey(rand.Reader)
shared, _ := priv.ECDH(peer.PublicKey()) // quantum-vulnerable
sk, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
sig, _ := ecdsa.SignASN1(rand.Reader, sk, digest[:])After: ML-KEM-768 key encapsulation
import (
"crypto/hkdf"
"crypto/mlkem"
"crypto/sha256"
)
// Receiver
dk, err := mlkem.GenerateKey768()
if err != nil { return err }
ekBytes := dk.EncapsulationKey().Bytes() // 1184 bytes, send to the sender
// Sender
ek, err := mlkem.NewEncapsulationKey768(ekBytes)
if err != nil { return err }
sharedKey, ciphertext := ek.Encapsulate() // 32-byte secret, 1088-byte ciphertext
// Receiver
recovered, err := dk.Decapsulate(ciphertext)
if err != nil { return err }
// Derive the actual AES-256-GCM key from the secret
aesKey, err := hkdf.Key(sha256.New, recovered, nil, "myapp/seal/v1", 32)
_ = sharedKeyAfter: ML-DSA-65 signatures (Go 1.27+)
import "crypto/mldsa"
sk, err := mldsa.GenerateKey(mldsa.MLDSA65())
if err != nil { return err }
pubBytes := sk.PublicKey().Bytes() // 1952 bytes
opts := &mldsa.Options{Context: "myapp/release/v1"}
sig, err := sk.Sign(nil, msg, opts) // 3309 bytes
if err != nil { return err }
pk, err := mldsa.NewPublicKey(mldsa.MLDSA65(), pubBytes)
if err != nil { return err }
if err := mldsa.Verify(pk, msg, sig, opts); err != nil { return err }Gotchas
- Store the seed.
dk.Bytes()returns the 64-byte seed form of an ML-KEM decapsulation key; recreate it withmlkem.NewDecapsulationKey768(seed). ML-DSAPrivateKey.Bytes()/mldsa.NewPrivateKey(params, seed)work the same way with a 32-byte seed. - Context strings must match between
SignandVerify. - Hybrid. Plain ML-KEM is standard-compliant, but for new protocols during the transition a hybrid (X25519 + ML-KEM, e.g. via
crypto/hpke) is the conservative choice. - FIPS module versions.
crypto/mldsais unavailable when Go is pinned to the FIPS 140-3 Go Cryptographic Module v1.0.0; it works with module v1.26.0 or later. - Sizes (ML-KEM-768 ciphertext 1,088 B; ML-DSA-65 signature 3,309 B) affect wire formats and storage.
- Older Go?
github.com/cloudflare/circlprovides ML-KEM and ML-DSA for toolchains before 1.24/1.27.
Verify
if !bytes.Equal(sharedKey, recovered) { log.Fatal("ML-KEM mismatch") }
fmt.Println(len(ciphertext), len(sig)) // 1088 3309@noble/post-quantum · typescriptJavaScript/TypeScript (any runtime): hybrid X25519 + ML-KEM-768 with @noble/post-quantumExperimental
Why
@noble/post-quantum is a small pure-JavaScript implementation of ML-KEM (FIPS 203), ML-DSA (FIPS 204) and SLH-DSA (FIPS 205). It runs anywhere JavaScript runs: Node 20/22, Deno, Bun, browsers and edge workers, which makes it the easiest option when you cannot rely on Node 24's native node:crypto support.
During the transition the recommended pattern is hybrid: combine a classical X25519 exchange with ML-KEM-768 so the result is secure if either holds. You can use the library's ready-made X-Wing construction, or build the combiner yourself with HKDF.
Maturity: the library is widely used and carefully written, but its README states it has not been independently audited. Prefer an OpenSSL/AWS-LC-backed API (Node 24.7+ node:crypto, WebCrypto where available) for high-assurance server code.
Steps
npm install @noble/post-quantum @noble/curves @noble/hashes- Decide between X-Wing (option A, a fixed, specified combiner; recommended) and a custom HKDF combiner (option B, if you must interoperate with an existing protocol).
- Store the recipient's private key as securely as any other private key; publish its public key.
- Use the 32-byte shared secret only as input to a KDF, then encrypt with AES-256-GCM or ChaCha20-Poly1305.
Before (X25519 / ECIES-style)
import { x25519 } from '@noble/curves/ed25519.js';
const recipient = x25519.keygen();
const eph = x25519.keygen();
const shared = x25519.getSharedSecret(eph.secretKey, recipient.publicKey); // quantum-vulnerableAfter, option A: X-Wing (X25519 + ML-KEM-768)
import { XWing } from '@noble/post-quantum/hybrid.js';
const recipient = XWing.keygen(); // publicKey: 1216 bytes
const { cipherText, sharedSecret } = XWing.encapsulate(recipient.publicKey); // cipherText: 1120 bytes
const recovered = XWing.decapsulate(cipherText, recipient.secretKey);
// sharedSecret and recovered are equal 32-byte keysX-Wing is specified in the IETF CFRG draft draft-connolly-cfrg-xwing-kem. Record the draft/library version you deployed so the other side can match it.
After, option B: explicit HKDF combiner
import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
import { x25519 } from '@noble/curves/ed25519.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { sha256 } from '@noble/hashes/sha2.js';
import { concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';
// Recipient long-term keys
const pq = ml_kem768.keygen(); // publicKey 1184 B, secretKey 2400 B
const ec = x25519.keygen();
// Sender
const { cipherText, sharedSecret: ssPq } = ml_kem768.encapsulate(pq.publicKey);
const eph = x25519.keygen();
const ssEc = x25519.getSharedSecret(eph.secretKey, ec.publicKey);
// Bind every public value into the derivation (domain separation + transcript)
const info = concatBytes(utf8ToBytes('myapp/hybrid-kem/v1'), eph.publicKey, ec.publicKey, cipherText, pq.publicKey);
const key = hkdf(sha256, concatBytes(ssPq, ssEc), undefined, info, 32);
// send: eph.publicKey (32 B) + cipherText (1088 B)
// Recipient
const ssPq2 = ml_kem768.decapsulate(cipherText, pq.secretKey);
const ssEc2 = x25519.getSharedSecret(ec.secretKey, eph.publicKey);
const key2 = hkdf(sha256, concatBytes(ssPq2, ssEc2), undefined, info, 32);Gotchas
- API versions. Code above is for
@noble/post-quantum0.5.x and@noble/curves/@noble/hashes2.x (note the.jssubpath imports). Argument orders and names have changed between major releases; check the README of the version you install. - Do not just XOR or concatenate secrets without a KDF, and include the ciphertext and public keys in the KDF input. Hand-made combiners are a classic source of subtle bugs, which is why option A exists.
- Implicit rejection.
decapsulatereturns a pseudo-random secret instead of throwing on a bad ciphertext; you detect tampering when the AEAD fails. - Sizes. Hybrid ciphertext ≈ 1.1 KB and public key ≈ 1.2 KB, versus 32 bytes for X25519 alone.
- Constant time. JavaScript engines give weaker side-channel guarantees than native code. That is fine for most client-side and server-side uses, but HSM-grade requirements need a native or hardware implementation.
- Pre-standard Kyber is not ML-KEM. Libraries or data created with "Kyber768" round-3 code are not interoperable with FIPS 203 ML-KEM.
Verify
console.assert(Buffer.from(key).equals(Buffer.from(key2)));
console.assert(cipherText.length === 1088 && pq.publicKey.length === 1184);cryptography (pyca) · pythonPython: replace RSA-OAEP / ECDH key wrapping with ML-KEM-768 in pyca/cryptography (48+)Production-ready
Why
Data encrypted to an RSA or elliptic-curve public key can be stored now and decrypted once a large quantum computer exists. ML-KEM (FIPS 203) replaces that step. cryptography (pyca) added an ML-KEM module in 47.0.0 (AWS-LC and BoringSSL backends) and extended it to the regular OpenSSL backend (OpenSSL 3.5.0 or later) in 48.0.0. The PyPI wheels bundle a recent OpenSSL, so pip install "cryptography>=48" gives you ML-KEM-768 and ML-KEM-1024 on Linux, macOS and Windows.
Steps
pip install -U "cryptography>=48"and pin it.- Recipient:
MLKEM768PrivateKey.generate(); publishpublic_key().public_bytes_raw()(1,184 bytes) or the SPKI encoding. - Sender:
shared_secret, ciphertext = public_key.encapsulate(); derive an AES key with HKDF; encrypt with AES-256-GCM. - Recipient:
private_key.decapsulate(ciphertext)gives the same secret. - For a hybrid (recommended during the transition), also do an X25519 exchange and feed both secrets into HKDF, as below.
Before
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
import os
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
data_key = os.urandom(32)
oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
wrapped = priv.public_key().encrypt(data_key, oaep)
assert priv.decrypt(wrapped, oaep) == data_keyAfter (hybrid ML-KEM-768 + X25519 → HKDF → AES-256-GCM)
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
# Recipient key pairs (store the private keys like any other secret)
pq_priv = MLKEM768PrivateKey.generate()
ec_priv = X25519PrivateKey.generate()
pq_pub, ec_pub = pq_priv.public_key(), ec_priv.public_key()
def derive(ss_pq: bytes, ss_ec: bytes, transcript: bytes) -> bytes:
return HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
info=b"myapp/hybrid-seal/v1" + transcript).derive(ss_pq + ss_ec)
def seal(plaintext: bytes, aad: bytes = b"") -> dict:
ss_pq, kem_ct = pq_pub.encapsulate() # (shared_secret, ciphertext)
eph = X25519PrivateKey.generate()
eph_pub = eph.public_key().public_bytes_raw()
ss_ec = eph.exchange(ec_pub)
key = derive(ss_pq, ss_ec, eph_pub + kem_ct)
nonce = os.urandom(12)
return {"kem_ct": kem_ct, "eph_pub": eph_pub, "nonce": nonce,
"body": AESGCM(key).encrypt(nonce, plaintext, aad)}
def open_(msg: dict, aad: bytes = b"") -> bytes:
ss_pq = pq_priv.decapsulate(msg["kem_ct"])
ss_ec = ec_priv.exchange(X25519PublicKey.from_public_bytes(msg["eph_pub"]))
key = derive(ss_pq, ss_ec, msg["eph_pub"] + msg["kem_ct"])
return AESGCM(key).decrypt(msg["nonce"], msg["body"], aad)
assert open_(seal(b"hello")) == b"hello"Gotchas
- Return order.
encapsulate()returns(shared_secret, ciphertext); mixing them up gives silently wrong keys. - Implicit rejection.
decapsulate()does not raise on a tampered ciphertext; you find out when AES-GCM raisesInvalidTag. - Sizes. ML-KEM-768 ciphertext 1,088 bytes, public key 1,184 bytes; ML-KEM-1024: 1,568 and 1,568. Private keys serialise as a 64-byte seed (
private_bytes_raw()). - Backend support. If your
cryptographyis built against a system OpenSSL older than 3.5 (some distro packages),generate()raisesUnsupportedAlgorithm. Check in CI. - Hazmat. These are low-level primitives; the HKDF
infolabel and transcript binding above matter. Prefer a reviewed higher-level protocol (HPKE, TLS) when one fits. - No ML-KEM-512 class in this module; use 768 (recommended) or 1024 (CNSA 2.0).
Verify
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
k = MLKEM768PrivateKey.generate()
ss, ct = k.public_key().encapsulate()
assert k.decapsulate(ct) == ss and len(ct) == 1088aws-lc-rs (kem) / RustCrypto ml-kem · rustRust: application-level ML-KEM-768 with aws-lc-rs or the RustCrypto ml-kem crateProduction-ready
Why
To replace ECDH- or RSA-based key wrapping in your own protocol, use ML-KEM (FIPS 203). Two common choices:
aws-lc-rs(aws_lc_rs::kem): bindings to AWS-LC, which also has a FIPS-validated mode. Recommended for production.ml-kem(RustCrypto): pure Rust,no_std-friendly. Its README warns it has never been independently audited; fine for many uses, but weigh that for high-assurance code.
Steps
- Add the crate, generate a decapsulation key, publish the encapsulation key bytes (1,184 bytes for ML-KEM-768).
- Sender encapsulates to get
(ciphertext, shared_secret); receiver decapsulates. - Feed the secret (optionally together with an X25519 secret for a hybrid) into HKDF and encrypt with AES-256-GCM or ChaCha20-Poly1305.
Before
use x25519_dalek::{EphemeralSecret, PublicKey};
let secret = EphemeralSecret::random();
let shared = secret.diffie_hellman(&peer_public); // quantum-vulnerableAfter: aws-lc-rs
use aws_lc_rs::kem::{Ciphertext, DecapsulationKey, EncapsulationKey, ML_KEM_768};
// Receiver
let dk = DecapsulationKey::generate(&ML_KEM_768)?;
let ek_bytes = dk.encapsulation_key()?.key_bytes()?; // send ek_bytes.as_ref() (1184 bytes)
// Sender
let ek = EncapsulationKey::new(&ML_KEM_768, ek_bytes.as_ref())?;
let (ciphertext, sender_secret) = ek.encapsulate()?;
// Receiver
let receiver_secret = dk.decapsulate(Ciphertext::from(ciphertext.as_ref()))?;
assert_eq!(sender_secret.as_ref(), receiver_secret.as_ref());After: RustCrypto ml-kem (0.3.x, getrandom feature enabled)
use ml_kem::{MlKem768, kem::{Decapsulate, Encapsulate, Kem}};
let (dk, ek) = MlKem768::generate_keypair();
let (ct, k_send) = ek.encapsulate();
let k_recv = dk.decapsulate(&ct);
assert_eq!(k_send, k_recv);Gotchas
- API churn. The RustCrypto
ml-kemAPI changed between 0.2 and 0.3; copy examples from the docs of the exact version you depend on. - Implicit rejection: decapsulating a wrong ciphertext returns a pseudo-random secret, not an error. Authenticate the payload with an AEAD.
- Do not use the raw secret directly as a long-term key; run it through HKDF with a protocol label.
- Hybrid with X25519 is recommended during the transition (combine both secrets in HKDF, binding the ciphertext and public keys).
Verify
Unit-test a round trip and assert sizes: ciphertext 1,088 bytes, encapsulation key 1,184 bytes, secret 32 bytes.