← Back to section · Tutorials & Labs
Wiring a KEM into a Toy Protocol: From Key Agreement to an Encrypted Conversation
Assemble a working two-party encrypted channel from four parts — ML-KEM agreement, HKDF derivation, key confirmation and AES-GCM encryption — with every gap between this toy and a real protocol labelled in place.
After learning the KEM three-step, a natural question follows: once we have a shared secret, what next? Real protocols never use the shared secret directly as a session key — key derivation and key confirmation sit in between. This tutorial assembles four parts into a complete toy protocol in Python: ML-KEM for agreement, HKDF for derivation, HMAC for key confirmation, and AES-GCM for encrypting the conversation. The code runs end to end, and every gap between it and a real protocol is labelled explicitly — understanding the gaps matters as much as understanding the code.
Warning: this is a teaching toy. It performs no authentication of the KEM public key whatsoever; a man in the middle can substitute public keys and negotiate separately with each side, and the protocol has no defence against it. Never use it to protect real communication.
The flow at a glance
The roles are initiator and responder. The responder generates an ML-KEM key pair and sends the public key to the initiator; the initiator encapsulates, obtaining a ciphertext and a shared secret, and sends the ciphertext back; the responder decapsulates and recovers the same shared secret. Each side then runs the shared secret through HKDF, mixing a hash of the public key and ciphertext into the derivation context — this is transcript binding: it ties the session key to this specific handshake, so changing any message yields a different key. Next the two sides exchange an HMAC tag for key confirmation: the tags can only match if the secrets truly agree. Once confirmation passes, application messages are encrypted with AES-GCM under fresh nonces.
The complete code, walked through
import hashlib
import hmac as hmac_mod
import os
import oqs
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
ALG = "ML-KEM-768"
def derive_session_key(shared_secret: bytes, transcript: bytes) -> bytes:
"""Derive a session key from the shared secret with HKDF,
binding this handshake's transcript via the info parameter."""
return HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b"toy-protocol-v1" + transcript,
).derive(shared_secret)
# ---- Responder: generate a key pair; the public key will be sent ----
with oqs.KeyEncapsulation(ALG) as responder:
responder_pk = responder.generate_keypair()
# ---- Initiator: encapsulate, obtaining ciphertext and shared secret ----
with oqs.KeyEncapsulation(ALG) as initiator:
ciphertext, secret_i = initiator.encap_secret(responder_pk)
# ---- Responder: decapsulate, recovering the shared secret ----
secret_r = responder.decap_secret(ciphertext)
# ---- Both sides: derive session keys (transcript = hash of pk || ct) ----
transcript = hashlib.sha256(responder_pk + ciphertext).digest()
key_i = derive_session_key(secret_i, transcript)
key_r = derive_session_key(secret_r, transcript)
# ---- Key confirmation: the responder proves "my key equals yours" ----
tag = hmac_mod.new(key_r, b"key-confirmation", hashlib.sha256).digest()
assert hmac_mod.compare_digest(
tag, hmac_mod.new(key_i, b"key-confirmation", hashlib.sha256).digest()
), "key confirmation failed: the two secrets differ"
# ---- Application data: AES-GCM with a fresh nonce per message ----
nonce = os.urandom(12)
box = AESGCM(key_i)
wire = nonce + box.encrypt(nonce, "Hello, post-quantum world".encode("utf-8"), None)
plain = AESGCM(key_r).decrypt(wire[:12], wire[12:], None)
print("decrypted:", plain.decode("utf-8"))
Section by section. Derivation uses the HKDF implementation from Python’s cryptography library, with the protocol name and the transcript hash placed in the info parameter: the protocol name prevents a secret from being reused across protocols, and the transcript hash welds the key to this one handshake. Key confirmation uses HMAC rather than comparing keys directly — neither side should ever send the session key or shared secret over the wire for comparison; comparing tags is enough. Encryption uses AESGCM with a random 12-byte nonce sent alongside the ciphertext; under one key a nonce must never repeat — that is GCM’s lifeline.
What happens if the ciphertext is tampered with
An experiment worth doing by hand: flip one byte of the ciphertext and run again. Decapsulation does not error (implicit rejection); the responder derives a different shared secret and hence a different session key — and then the assertion at key confirmation fails and the protocol terminates cleanly. Compare that with a version lacking key confirmation: both sides proceed into the application phase holding different keys, and nothing fails until the first message refuses to decrypt, with the error reported a world away from the actual cause (a tampered ciphertext). This contrast shows most directly why key confirmation is not decoration: it is the device that moves failure detection forward into the handshake.
One step further: separate keys per direction
The toy uses a single session key for messages in both directions, which real protocols do not allow. Standard practice slices different keys for the two directions right at the derivation stage — one for initiator-to-responder, another for responder-to-initiator, plus separate material for key confirmation. There are three reasons. First, reflection attacks: if both directions share one key, an attacker can send a party’s own ciphertext straight back to it, and that party will decrypt it as if it came from the peer; with per-direction keys, a reflected ciphertext simply does not decrypt. Second, nonce-space management: AES-GCM forbids nonce reuse under one key, and separate keys per direction keep the two nonce spaces naturally disjoint. Third, clean accountability: if one key is compromised or must be retired, the boundary of what to revoke is obvious. Implementation costs almost nothing: derive twice from HKDF with a direction label in info (for example toy-v1 c2s and toy-v1 s2c). Add this step to the code above and the toy’s structural completeness moves one notch closer to a real protocol — leaving public-key authentication, the checklist item that calls for signatures, as the main remaining gap.
Mistakes and simplifications checklist
- Using the shared secret directly as an AES key. A shared secret’s distribution and format are not designed for direct use; it must pass through a KDF. Real protocols also slice several purpose-separated keys (encryption, confirmation, IV material) out of one derivation instead of sharing one key everywhere.
- Skipping key confirmation. As shown above, tampering and mis-wiring then surface late, in bizarre forms, during the application phase.
- Reusing GCM nonces, or restarting a counter from zero across sessions. A repeated nonce under one key breaks both confidentiality and integrity; the toy uses random nonces, while real protocols manage the nonce space systematically.
- No public-key authentication (this toy’s biggest simplification). A real protocol must answer “does this public key really belong to my peer?” — usually with signatures (see the signature tutorial in this section) or pre-shared information; TLS hangs its certificate system on exactly this hook.
- No forward secrecy and no replay protection. The toy’s responder key pair is long-lived, so leaking it exposes every past session; real protocols use one-time ephemeral keys plus sequence numbers and time windows against replay.
Summary
A KEM is only the first brick of a protocol: derivation turns the secret into usable key material, confirmation aligns both sides’ state before any data flows, and AEAD encryption carries the data itself. Assemble the four parts once by hand, then read them against the simplification checklist, and the structure of real protocols such as TLS 1.3 becomes a clear map. As the next exercise, add a fifth brick: sign the responder’s KEM public key with ML-DSA and have the initiator verify the signature before encapsulating — supplying the authentication ring yourself.
Tags: ML-KEMProtocol DesignHKDFProgramming