← Back to section · Tutorials & Labs
Hands-On: Your First ML-KEM Key Encapsulation with liboqs
Use the Open Quantum Safe Python bindings locally to run ML-KEM-768 key generation, encapsulation and decapsulation — and verify that both sides arrive at exactly the same shared secret.
What we are doing
After reading about KeyGen, Encaps and Decaps in ML-KEM Explained, the fastest way to really understand them is to run them. This tutorial uses the Open Quantum Safe (OQS) Python bindings, liboqs-python, to perform a complete ML-KEM-768 encapsulation locally, and to verify that the two parties’ shared secrets match byte for byte.
Note: OQS is an experimental project aimed at research and prototyping, and its documentation explicitly warns against production use. This tutorial has the same purpose: learning and verifying concepts.
Setup
You need Python 3.10 or newer. liboqs-python depends on the underlying liboqs C library, whose installation differs by operating system (source build, package manager, or the official Docker image) — follow the current instructions in the liboqs-python repository README. The Python package itself installs with:
pip install liboqs-python
Then confirm ML-KEM is available:
import oqs
print("ML-KEM-768 enabled:", "ML-KEM-768" in oqs.get_enabled_kem_mechanisms())
The full experiment
import oqs
ALG = "ML-KEM-768"
# 1) Receiver: generate a key pair (KeyGen)
with oqs.KeyEncapsulation(ALG) as decapsulator:
public_key = decapsulator.generate_keypair()
print("Encapsulation key length:", len(public_key), "bytes") # expect 1184
# 2) Sender: encapsulate against the public key (Encaps)
with oqs.KeyEncapsulation(ALG) as encapsulator:
ciphertext, shared_secret_enc = encapsulator.encap_secret(public_key)
print("Ciphertext length:", len(ciphertext), "bytes") # expect 1088
# 3) Receiver: decapsulate with the private key (Decaps)
shared_secret_dec = decapsulator.decap_secret(ciphertext)
# 4) Verify: both shared secrets must be identical
assert shared_secret_enc == shared_secret_dec, "Shared secrets differ!"
print("Verified: shared secrets match, length", len(shared_secret_enc), "bytes")
You should see a 1184-byte public key, a 1088-byte ciphertext and a 32-byte shared secret — exactly the ML-KEM-768 row of the FIPS 203 parameter table. Try re-running with ALG set to ML-KEM-512 and ML-KEM-1024 to compare the three parameter sets.
Experiment 2: Tamper with the Ciphertext and Watch Implicit Rejection
Pitfall 1 below claims a failed decapsulation raises no error — do not just memorize that; verify it by hand. Flip one bit of the ciphertext and decapsulate:
import oqs
ALG = "ML-KEM-768"
with oqs.KeyEncapsulation(ALG) as decapsulator:
public_key = decapsulator.generate_keypair()
with oqs.KeyEncapsulation(ALG) as encapsulator:
ciphertext, shared_secret_enc = encapsulator.encap_secret(public_key)
# Flip one bit in the first ciphertext byte
tampered = bytes([ciphertext[0] ^ 0x01]) + ciphertext[1:]
shared_secret_bad = decapsulator.decap_secret(tampered)
print("Do the good and tampered secrets match?", shared_secret_enc == shared_secret_bad)
# Output: False — and decap_secret raised nothing
decap_secret never raises; it quietly returns a different secret. That is implicit rejection: ML-KEM’s Decaps uses the Fujisaki–Okamoto transform to hide “invalid ciphertext” inside key derivation — decapsulation re-encrypts internally and compares ciphertexts, and on a mismatch it derives the output from a secret random value stored in the private key instead of the real secret, producing a fake secret that looks completely normal.
Why design it this way? Because an explicit error is itself an information leak: an attacker can probe a server with modified ciphertexts and use the error/no-error distinction to extract the private key bit by bit (a decryption-failure oracle attack). Implicit rejection closes that channel — at the price that the application layer must add its own key-confirmation step: before real data flows, both sides exchange an authenticated message under the derived key and abort if it does not check out. The TLS 1.3 Finished message does exactly this.
Add one more check yourself: generate two key pairs, encapsulate against A’s public key but decapsulate with B’s private key, and observe — again no error, and a different secret. Together with the tampering run, you have now triggered implicit rejection both ways it can happen.
Experiment 3: Size Comparison Across the Three Parameter Sets
Wrap the main experiment in a loop, run all three parameter sets, and line every size up against the FIPS 203 parameter table:
import oqs
for alg in ["ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"]:
with oqs.KeyEncapsulation(alg) as decap:
pk = decap.generate_keypair()
with oqs.KeyEncapsulation(alg) as encap:
ct, ss = encap.encap_secret(pk)
print(f"{alg}: public key {len(pk)} B, ciphertext {len(ct)} B, shared secret {len(ss)} B")
Expected output:
ML-KEM-512: public key 800 B, ciphertext 768 B, shared secret 32 B
ML-KEM-768: public key 1184 B, ciphertext 1088 B, shared secret 32 B
ML-KEM-1024: public key 1568 B, ciphertext 1568 B, shared secret 32 B
Three things to notice in this table. First, the shared secret is always 32 bytes — the parameter sets change the security margin (NIST categories 1, 3, and 5), not the output length; “the 1024 set’s key is longer, so it must be safer” is a common misconception. Second, public keys and ciphertexts grow roughly linearly with the set, a structural property of lattice schemes: the module rank k grows from 2 to 4, and every polynomial has to be transmitted. Third, the private key is not printed — liboqs-python’s export_secret_key() can export it (2,400 bytes for the 768 set), but note that its encoding bundles a copy of the public key plus a checksum value, so its length means something different from the public key’s.
This size table is not decoration: whether a TLS handshake fits in a single TCP flight, how much a certificate chain grows, whether an IoT device has the flash — all of it is computed from these numbers. Later TLS labs on this site use them directly.
Experiment 4: From Shared Secret to Session Key
The main experiment’s assert only proves both sides hold the same secret; it is not yet usable for encryption. Engineering practice adds a KDF step. Complete the chain with HKDF from the cryptography package:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
session_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b"pq-frontier lab session v1", # context label: must differ per purpose
).derive(shared_secret_enc)
print("Session key length:", len(session_key))
Every parameter here earns its place: info is a domain-separation label — the same shared secret must yield different keys in different protocols and for different purposes, and the label is what enforces that. If sender and receiver differ by one byte in info, the derived keys differ completely and communication fails outright — which is precisely where the key confirmation of Experiment 2 lands in real systems. HKDF itself has an Extract and an Expand stage; this cryptography interface merges the two. Detail-oriented readers can re-implement it with hmac following RFC 5869 — the outputs should match byte for byte.
With this step the chain is complete: KeyGen makes the keys, Encaps/Decaps agree the secret, HKDF derives session keys, and symmetric encryption (AES-GCM, say) protects the data. Real protocols such as TLS 1.3 run exactly this chain, adding certificate authentication and a finer-grained key hierarchy.
Three pitfalls worth knowing
- The public key must come from the same KeyGen run. Encapsulate against a stale public key and decapsulate with a newer private key, and the secrets will differ — silently. Decapsulation does not raise an error; it quietly returns a wrong result (that is exactly what implicit rejection is designed to do). Real systems must catch this with a key-confirmation step.
- The shared secret is not itself a session key. In engineering practice it goes into a KDF (such as HKDF) to derive session keys; do not use it directly as an AES key.
- Randomness quality is everything. It does not matter in a lab, but in any serious setting the randomness for KeyGen and Encaps must come from the operating system’s cryptographic random source.
Next steps
- Turn the experiment into hybrid mode: run an X25519 exchange alongside the ML-KEM encapsulation and feed both secrets into the KDF — which is precisely what TLS 1.3 does today.
- Read Chapter 7 of FIPS 203 and map each algorithm’s inputs and outputs to this experiment.
References
- Open Quantum Safe project. https://openquantumsafe.org
- liboqs-python repository (installation and API). https://github.com/open-quantum-safe/liboqs-python
- NIST, FIPS 203, 2024-08-13. https://doi.org/10.6028/NIST.FIPS.203
Tags: liboqsML-KEMPythonLab