← Back to section · Tutorials & Labs

A Hybrid Key Exchange Skeleton: How X25519 and ML-KEM Fit Together

A complete code skeleton for hybrid key exchange with X25519 plus ML-KEM-768: two independent agreements, a combiner, transcript binding — and a clear account of how it relates to, and differs from, the TLS hybrid groups and X-Wing.

Published 22 November 2026 · 6 min read · PQ Frontier

A Hybrid Key Exchange Skeleton: How X25519 and ML-KEM Fit Together
AI-generated site artwork
Video explainer · PQC programming: calling real libraries

Deploying ML-KEM alone into a new system is an easy decision. The hard question arises when upgrading an existing system: X25519 has served well for years, yet swapping it out wholesale feels risky in case the post-quantum algorithm harbours an undiscovered weakness, while keeping only the classical algorithm leaves the quantum threat unanswered. The industry’s answer is hybrid key exchange — run both and combine them, so that the negotiated key is secure as long as either component remains secure. This tutorial presents a complete code skeleton that performs two independent agreements, X25519 and ML-KEM-768, and combines them into a session key, then spells out exactly where the skeleton stops and the real standards begin.

The shape: agree twice, combine once

The flow has three parts. First, one side generates an ephemeral X25519 key pair and an ML-KEM key pair — in key-exchange settings the KEM key pair is generated by whichever side plays the “server” role for that protocol; the skeleton keeps the previous tutorial’s arrangement, with the responder generating the KEM key pair. Second, the peer completes the X25519 exchange and the ML-KEM encapsulation, so each side now holds two shared secrets: one classical, one post-quantum. Third comes the combiner: concatenate the two secrets into HKDF, with both X25519 and ML-KEM public keys and the ciphertext hashed into the info context, and derive the final session key.

The complete skeleton code

import hashlib

import oqs
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey,
    X25519PublicKey,
)
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat

KEM_ALG = "ML-KEM-768"

def raw_pub(key) -> bytes:
    """Serialize an X25519 public key to its 32-byte raw form."""
    return key.public_bytes(Encoding.Raw, PublicFormat.Raw)

def combine(ss_classic: bytes, ss_pq: bytes, transcript: bytes) -> bytes:
    """Combiner: concatenate both shared secrets into HKDF,
    with the transcript hash bound into info."""
    return HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=b"hybrid-x25519-mlkem768-v1" + transcript,
    ).derive(ss_classic + ss_pq)

# ---- Responder: generate an ephemeral X25519 key and an ML-KEM key pair ----
resp_x = X25519PrivateKey.generate()
resp_x_pub = raw_pub(resp_x.public_key())
with oqs.KeyEncapsulation(KEM_ALG) as responder_kem:
    resp_kem_pk = responder_kem.generate_keypair()

    # ---- Initiator: complete the X25519 exchange and the ML-KEM encapsulation ----
    init_x = X25519PrivateKey.generate()
    init_x_pub = raw_pub(init_x.public_key())
    ss_classic_i = init_x.exchange(
        X25519PublicKey.from_public_bytes(resp_x_pub)
    )
    with oqs.KeyEncapsulation(KEM_ALG) as initiator_kem:
        kem_ct, ss_pq_i = initiator_kem.encap_secret(resp_kem_pk)

    # ---- Responder: complete the X25519 exchange and decapsulate ----
    ss_classic_r = resp_x.exchange(
        X25519PublicKey.from_public_bytes(init_x_pub)
    )
    ss_pq_r = responder_kem.decap_secret(kem_ct)

    # ---- Both sides: combine (transcript = hash of both public keys and the ct) ----
    transcript = hashlib.sha256(resp_x_pub + resp_kem_pk + init_x_pub + kem_ct).digest()
    key_i = combine(ss_classic_i, ss_pq_i, transcript)
    key_r = combine(ss_classic_r, ss_pq_r, transcript)
    assert key_i == key_r, "hybrid agreement failed: keys differ"
    print("hybrid key exchange complete, session key length:", len(key_i), "bytes")

Implementation notes. The X25519 half uses the cryptography library: exchange takes the peer’s public-key object; public keys travel on the wire serialized with Encoding.Raw and PublicFormat.Raw into 32 bytes, and are restored on receipt with X25519PublicKey.from_public_bytes. The concatenation order of the two secrets is part of the protocol and must be fixed identically on both sides (here: classical first, post-quantum second) — different orders derive different keys. The transcript covers both public keys and the ciphertext, so substituting any of them makes the final keys disagree — and with the previous tutorial’s key confirmation added, the substitution is caught during the handshake.

How the skeleton differs from the real schemes

Two deployed references exist. The hybrid key shares in TLS 1.3 (such as the X25519MLKEM768 group) concatenate the two public-key shares and ciphertexts in TLS’s own message formats, and combine the secrets through TLS’s key schedule (the HKDF Extract/Expand chain), with every detail fixed by the protocol specification. X-Wing, by contrast, is a standalone general-purpose hybrid KEM design whose combiner is more particular: it applies a specific SHA3-256 construction over the two secrets and the ML-KEM ciphertext and public key in a prescribed encoding, in order to obtain provable combiner properties.

The skeleton differs from both in the concrete construction and encoding rules of its combining function: “concatenate and run HKDF” achieves the combining properties a teaching demo needs (secure if either component is secure, transcript-bound), but it is not a verbatim implementation of any standard. The conclusion must be stated plainly: use the skeleton to understand the structure; use standard implementations in production — a mature TLS library with hybrid-group support for TLS scenarios, and for X-Wing a byte-for-byte implementation of its specification, validated against its test vectors.

Do the math first: where the hybrid byte cost is paid

Hybrid is not free, and its cost is paid mostly in bytes on the wire — bytes you can compute exactly in advance. In the deployed TLS hybrid groups, the client’s key_share is the concatenation of the 32-byte X25519 public key and the 1184-byte ML-KEM-768 public key, while the server’s reply carries the 1088-byte ML-KEM ciphertext alongside its X25519 share. That extra kilobyte-plus inflates the handshake flights, and on some network paths it triggers additional fragmentation and retransmission — the main source of latency variance observed in early hybrid deployments. Doing this arithmetic matters because it drives decisions: for long-lived connections inside a data centre the byte cost is negligible, but for size-sensitive protocols (DNS, IoT, low-bandwidth links) it can dominate the algorithm choice. After the skeleton runs, print the actual lengths of the three pieces of material and check them against the FIPS 203 parameter tables and X25519’s 32 bytes — a handy way to confirm the combiner code has not wired any material into the wrong slot.

Common mistakes checklist

  1. Combining the secrets without binding the transcript. If public keys and ciphertext are not bound into the derivation context, an attacker who substitutes one of them may still leave both sides with consistent but manipulated keys — downgrade attacks get their opening.
  2. Inconsistent concatenation order between the sides. The input order to the combiner is a protocol parameter; it must be written into the spec and hardcoded identically at both ends.
  3. Combining with XOR or a bare hash. XOR-combining leaks one component directly when the other is attacker-controlled; combining must go through an analysed KDF construction.
  4. Reusing the X25519 key long-term. The hybrid’s forward secrecy comes from ephemeral keys on both legs; pinning the X25519 key in place dismantles half the design intent.
  5. Shipping skeleton code to production. Encodings, combiner construction and error handling all fall short of a standard implementation’s rigour — no exceptions to this one.

Summary

Hybrid key exchange compresses into one sentence: two legs negotiate independently, and the combiner brews the two secrets together with the full transcript into the final key. The skeleton lets you run that chain by hand — and break and repair it by hand; real deployments belong to libraries that implement the standards verbatim. With this article, the eight tutorials of this subcategory have travelled from calling a single algorithm to composing a combined protocol: first use one algorithm, then verify it, benchmark it, and finally assemble it with others into a system — the complete progression path of post-quantum programming.

Tags: Hybrid Key ExchangeX25519ML-KEMProgramming