← Back to section · Tutorials & Labs

Toy Experiment: Stitching X25519 and ML-KEM into a Hybrid Key Exchange with oqs-python

The hybrid idea is to let a classical algorithm and a post-quantum algorithm each contribute half of the secret and combine the halves into one key — if either half falls, the other still holds. This tutorial builds a runnable teaching version with liboqs-python's KEM interface and cryptography's X25519, and explains why the combiner must be more than plain concatenation.

Published 22 November 2026 · 7 min read · PQ Frontier

Toy Experiment: Stitching X25519 and ML-KEM into a Hybrid Key Exchange with oqs-python
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

Aim and scope of this tutorial

Let us be blunt up front: this is a teaching toy. It runs the skeleton of a hybrid key exchange so you can see the data flow; it is not an implementation to lift into a production system. Hybrid is the mainstream strategy of the current post-quantum migration: real protocols such as TLS combine classical X25519 with post-quantum ML-KEM in a single handshake, taking the union of their security — if quantum computers mature and the classical half fails, the post-quantum half still stands; conversely, if a post-quantum algorithm falls to a new classical attack, the classical half still covers you. This tutorial uses liboqs-python (the Python bindings of the Open Quantum Safe project, package name oqs) to encapsulate and decapsulate with ML-KEM-768, stitches that together with the X25519 exchange from the previous tutorial, and combines everything into a session key with HKDF. Before running it, install liboqs-python and its underlying liboqs library following the project’s official instructions.

Step one: run ML-KEM through the oqs interface

A KEM (key encapsulation mechanism) has a slightly different interaction shape from classic Diffie-Hellman: it is an asymmetric three-step dance. The receiver generates a key pair and publishes the public key; the sender “encapsulates” against that public key, randomly producing a shared secret together with the corresponding ciphertext; the receiver “decapsulates” the ciphertext with the private key and recovers the same shared secret. The central class of the oqs package is oqs.KeyEncapsulation: construct it with the algorithm name, then call generate_keypair(), encap_secret(public_key) and decap_secret(ciphertext) in turn. Note that encap_secret returns both the ciphertext and the shared secret — that is precisely what separates a KEM from ordinary public-key encryption: the encapsulated secret is generated randomly inside the algorithm, not chosen by the sender.

import oqs

# Receiver: generate an ML-KEM-768 key pair; public key out, private key home
with oqs.KeyEncapsulation("ML-KEM-768") as receiver:
    mlkem_public = receiver.generate_keypair()

    # Sender: encapsulate against the public key -> ciphertext + shared secret
    with oqs.KeyEncapsulation("ML-KEM-768") as sender:
        mlkem_ciphertext, kem_shared_sender = sender.encap_secret(mlkem_public)

    # Receiver: decapsulate with the private key -> the same shared secret
    kem_shared_receiver = receiver.decap_secret(mlkem_ciphertext)

assert kem_shared_sender == kem_shared_receiver
print("ML-KEM shared secret length:", len(kem_shared_sender))  # 32 bytes

Step two: stitch in X25519 to form the hybrid exchange

The full hybrid data flow runs like this: both sides generate ephemeral X25519 key pairs and swap public keys, while in parallel the receiver generates an ML-KEM key pair and the sender encapsulates and returns the ciphertext. Each side now holds two secrets — the output of X25519’s exchange() and the ML-KEM shared secret. How they are combined determines the security floor of the hybrid scheme. The crudest approach, concatenating the two secrets and using the result directly as a key, is wrong: the raw secrets are not uniformly distributed and bind no context. The minimum acceptable standard for teaching purposes is to concatenate the secrets into HKDF and fold both public keys and the ML-KEM ciphertext into the info context, binding the final key to this specific handshake:

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

# The X25519 half (receiver's view; the sender mirrors the exchange)
x_private = X25519PrivateKey.generate()
x_public_bytes = x_private.public_key().public_bytes(
    serialization.Encoding.Raw, serialization.PublicFormat.Raw)
# ... after receiving peer_public_bytes and rebuilding the peer key:
# x_shared = x_private.exchange(X25519PublicKey.from_public_bytes(peer_public_bytes))

def combine(kem_shared: bytes, x_shared: bytes, transcript: bytes) -> bytes:
    return HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=b"hybrid-x25519-mlkem768-v1|" + transcript,
    ).derive(kem_shared + x_shared)

# transcript should concatenate both X25519 public keys,
# the ML-KEM public key and the ciphertext
# session_key = combine(kem_shared_receiver, x_shared, transcript)

Walking the data flow in time order

To make the skeleton clearer, unfold one complete hybrid exchange in time order. Step one: before the connection begins, the receiver generates its ML-KEM key pair — this private key may be generated in advance and stored carefully, while the public key travels with the connection setup; at the same time, both sides generate one-time ephemeral X25519 key pairs. Step two: the two lines flow in parallel — the two X25519 public keys cross on the channel, and the ML-KEM public key and, shortly after, the ciphertext flow as well; an eavesdropper sees all four pieces of public material yet can derive neither secret. Step three: the sender completes two local operations — exchange() against the received X25519 public key and encap_secret() against the ML-KEM public key — then sends the ciphertext back. Step four: the receiver recovers the KEM secret with decap_secret() under its ML-KEM private key, and computes the other half with its own X25519 private key. Step five: both sides feed the two secrets and the handshake transcript into HKDF, arrive at the same session key, and exchange a key-confirmation message to verify alignment. Note the key point in this ordering: the ML-KEM private key is the only long-lived secret in the whole chain; everything else is session-scoped and destroyed after use — which means the key-management burden of a hybrid scheme still rests on protecting that one KEM private key, the same discipline as protecting a server’s private key in the classical world.

The size bill: hybrid is not free

Before writing code, do the size arithmetic so the cost of hybrid stays in view. An X25519 public key is 32 bytes, almost nothing; an ML-KEM-768 public key is 1184 bytes and its ciphertext 1088 bytes, so one hybrid handshake moves roughly 2.3 KB of post-quantum material across the channel — several times a purely classical handshake. That magnitude is no burden for ordinary web traffic, but three scenarios must assess it seriously: IoT links with tight message-size limits, protocols that squeeze public keys into narrow channels such as DNS records or QR codes, and very large services handling masses of new connections where every byte of bandwidth is accounted for. The parameter set changes the bill too: ML-KEM-512’s public key and ciphertext are each a step smaller, ML-KEM-1024’s larger, and choosing a set is fundamentally a trade-off between security margin and transport cost that the deployment scenario, not personal taste, should decide. Doing this arithmetic first, and only then fixing the scope and parameter set of the hybrid, is the first lesson in upgrading toy thinking into engineering judgement.

The gap between the toy and real protocols

Real-world hybrid designs — for example TLS’s X25519MLKEM768 group — add three more layers on top of this skeleton. The first is a rigorously defined combiner: industrial combiners feed the length of each secret, the algorithm identifiers and the complete handshake transcript into the derivation, so that if any component is missing or mismatched the derived keys diverge completely. That defeats downgrade attacks: if an attacker “negotiates away” the post-quantum half, the two sides’ keys should fail to match rather than silently falling back to classical-only. The second layer is implementation provenance: liboqs is a reference implementation for research and interoperability testing, and its maintainers explicitly advise against using it directly in production; production systems should use the hybrid groups built into audited, maintained TLS libraries. The third layer is the engineering bill for performance and size: ML-KEM-768’s public key and ciphertext are each on the order of a thousand bytes, making a hybrid handshake noticeably larger than a purely classical one, and the impact on handshake latency and middleboxes must be assessed before deployment. Keep those three gaps in mind and the toy has done its teaching job: it let you touch every wire of a hybrid exchange with your own hands — but when you go on the road for real, use the finished product provided by a standard protocol stack.

Tags: PythonliboqsML-KEMHybrid Key Exchange