← Back to section · Tutorials & Labs
Project: A Two-Process Local KEM Key Exchange Demo Service
Run a server and a client as two local processes over Python sockets, complete a full ML-KEM-768 encapsulation exchange, then carry an encrypted echo channel on the negotiated shared secret.
Moving a KEM from “two function calls in one process” to “two processes exchanging bytes over a socket” reveals the protocol’s real shape: who speaks first, how long each field is, what happens on a partial read, and whether the key ever leaves the machine. This project is a minimal server/client pair. The server generates an ML-KEM-768 key pair at startup and listens on a local port. Once the client connects, the server sends its public key; the client encapsulates and returns a ciphertext; the server decapsulates — and both sides hold the same shared secret without the key ever being transmitted. Each side then derives a session key from the shared secret with HKDF; the client sends an AES-GCM encrypted message, the server decrypts it and echoes it back encrypted, and the client decrypts and checks it, closing the loop. The boundary: it listens on loopback only and has no authentication or replay protection whatsoever. It is a protocol teaching demo, not a secure communication service you could deploy. For real secure communication, use TLS — the value of this project is showing you roughly what a TLS handshake is busy doing inside.
Goal and Architecture
There are exactly four messages. Server to client: the public key (1184 bytes). Client to server: the KEM ciphertext (1088 bytes). Client to server: one AEAD ciphertext (the test message). Server to client: one AEAD ciphertext (the echo). Neither the shared secret nor the session key appears in any message — the essential difference between a KEM and the old practice of “encrypt the key and send it over”, and a fact you should confirm with your own eyes during verification: a packet capture shows only a public key, a ciphertext, and ciphertexts.
The most underestimated part of the protocol is framing. TCP guarantees ordered bytes, not whole fields: a single recv may deliver the 1184-byte public key in two chunks, or glued to the following bytes. So every message uses a uniform format — a 4-byte big-endian length prefix plus payload — and the receiver first reads exactly 4 bytes to learn the length, then loops on recv until the full payload has arrived. The recv_exactly helper is barely a dozen lines, yet it is the most memorable code in the whole project: most beginner network bugs live here, not in the cryptography.
Walking Through the Core Code
The server core (argument parsing and logging omitted):
import socket, oqs, hashlib
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
def recv_exactly(conn, n: int) -> bytes:
buf = b""
while len(buf) < n:
chunk = conn.recv(n - len(buf))
if not chunk:
raise ConnectionError("peer disconnected mid-field")
buf += chunk
return buf
def recv_msg(conn) -> bytes:
length = int.from_bytes(recv_exactly(conn, 4), "big")
return recv_exactly(conn, length)
def send_msg(conn, data: bytes) -> None:
conn.sendall(len(data).to_bytes(4, "big") + data)
kem = oqs.KeyEncapsulation("ML-KEM-768")
public_key = kem.generate_keypair()
# after the client connects:
send_msg(conn, public_key)
ct = recv_msg(conn)
shared = kem.decap_secret(ct)
session_key = HKDF(algorithm=hashes.SHA256(), length=32,
salt=None, info=b"kem-demo v1").derive(shared)
The client is symmetric: after connecting it recv_msgs the public key, calls encap_secret(public_key) on a separate KeyEncapsulation object to obtain the ciphertext and shared secret, send_msgs the ciphertext back, and derives the session key with identical HKDF parameters. Three details. First, the server’s kem object must stay alive and hold the private key until decapsulation — generate_keypair stores the private key inside the object, and if the object is collected, the key is gone; the client only needs a keyless encapsulation object. Second, the HKDF info must match character for character on both ends; it acts as the protocol’s shared passphrase, and a mismatch makes the two sides derive different session keys, after which every AEAD decryption fails cleanly — a built-in self-check: in this protocol any parameter mismatch surfaces as decryption failure rather than silent divergence. Third, the AEAD nonce (details abbreviated in the listing) follows one rule only: never reuse a nonce under the same session key; a direction byte plus an incrementing counter is the scheme that is easiest to get right in teaching code.
Running and Verifying
Open two terminals, start the server first, then the client, and check four things. First, the shared-secret fingerprint in both logs (print only the first 8 hex characters of its SHA-256 — never print the key itself; that is a professional habit worth forming even in teaching projects) must agree. Second, the echo loop: the plaintext the client sent and the echo it received must be identical, character for character. Third, capture inspection: use Wireshark or tcpdump on the loopback interface and confirm that only the public key, the ciphertext, and AEAD ciphertexts appear on the wire — the shared secret’s bytes occur in no packet. Fourth, the failure path: have the client deliberately flip one byte of the ciphertext before sending; the server’s decapsulation yields a different “shared secret”, the following AEAD decryption fails, and the connection terminates with an error. Note that KEM decapsulation itself raises no error — ML-KEM uses implicit rejection, so a bad ciphertext simply yields a wrong shared secret; the failure only surfaces at the symmetric decryption step. Verifying this by hand once is worthwhile: it is exactly why real protocols perform key confirmation before using a key.
Exercises
One: upgrade the echo channel to a multi-round dialogue of ten messages and watch how the nonce counters increment independently in each direction. Two: add a key-confirmation step — before the data channel opens, both sides exchange an HMAC tag computed with the session key, moving “we only noticed the keys disagree when decryption failed” forward into the handshake. Three: replace pure ML-KEM with an ML-KEM + X25519 hybrid (see the hybrid KEM file encryption project in this subcategory) and compare the two wire formats. Four, the advanced one: support multiple clients with a thread per connection, and think through the trade-off between generating a fresh key pair per connection and sharing one key pair across the whole server.
Summary
The entire value of this demo service is spreading a key exchange across two processes where you can watch it: the three-move wire format, length-prefixed framing, the temperament of implicit rejection, and the necessity of key confirmation are all invisible when you merely call functions inside one process. The boundary, restated: no authentication, no replay protection, loopback only — a teaching aid, not a service. Once you understand it, hand production communication to TLS; what this project teaches is precisely why TLS is designed the way it is.
Tags: KEMSocket ProgrammingML-KEMProtocol Demo