← Back to section · Tutorials & Labs

X25519 Key Exchange with cryptography: From Shared Secret to Session Key

The core idea of Diffie-Hellman is that two parties derive the same secret over a public channel. This tutorial performs a complete elliptic-curve key exchange with the cryptography library's X25519 interface, then processes the raw shared secret into a usable session key with HKDF, and explains the checks you must not skip.

Published 22 November 2026 · 7 min read · PQ Frontier

X25519 Key Exchange with cryptography: From Shared Secret to Session Key
AI-generated site artwork
Video explainer · Python cryptography: experiments and prototypes

What this tutorial aims to do

Suppose two machines need an encrypted channel, share no prior secret, and must assume the line is being recorded end to end — that is exactly the problem key exchange solves. This tutorial performs a real X25519 elliptic-curve key exchange with Python’s cryptography library: generate key pairs, swap public keys, compute the shared secret, and derive a session key from it with HKDF. All code uses the library’s real interfaces and runs locally as-is. By the end you should be able to explain three things: why both sides necessarily arrive at the same result, why the shared secret cannot be used as a key directly, and which steps still separate a demo from production.

The basic idea of X25519

The magic of Diffie-Hellman key exchange is an asymmetric structure: each party generates a private/public key pair, keeps the private key, and sends the public key to the peer. On receiving the peer’s public key, each side runs one computation combining “my private key” with “your public key”. The remarkable part is that Alice’s result from “Alice’s private × Bob’s public” is byte-for-byte identical to Bob’s result from “Bob’s private × Alice’s public”. An eavesdropper who captured both public keys would have to solve the elliptic-curve discrete logarithm problem to reproduce that value, which is infeasible with current computing power. X25519 is this idea instantiated on the Curve25519 curve: private keys are 32 random bytes, public keys are 32 bytes, and its careful design makes it hard to implement incorrectly — one reason TLS 1.3, SSH and WireGuard all adopted it.

Step one: generate key pairs and swap public keys

In the cryptography library, the X25519 interface lives in cryptography.hazmat.primitives.asymmetric.x25519. Generate a private key with the class method X25519PrivateKey.generate(), and derive the public key with public_key(). To send a public key to the peer it must be serialized to bytes: X25519 public keys are normally transmitted as raw 32 bytes, obtained via public_bytes(Encoding.Raw, PublicFormat.Raw); on receipt, X25519PublicKey.from_public_bytes(data) rebuilds the public-key object. The code below simulates Alice and Bob each generating a pair and exchanging public keys:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey, X25519PublicKey)

# Alice generates a key pair; the private key stays local
alice_private = X25519PrivateKey.generate()
alice_public_bytes = alice_private.public_key().public_bytes(
    serialization.Encoding.Raw, serialization.PublicFormat.Raw)

# Bob does the same
bob_private = X25519PrivateKey.generate()
bob_public_bytes = bob_private.public_key().public_bytes(
    serialization.Encoding.Raw, serialization.PublicFormat.Raw)

# They swap public-key bytes over the public channel and rebuild objects
alice_peer = X25519PublicKey.from_public_bytes(bob_public_bytes)
bob_peer = X25519PublicKey.from_public_bytes(alice_public_bytes)
print(len(alice_public_bytes), len(bob_public_bytes))  # both 32

Step two: compute the shared secret, then derive with HKDF

Each side calls exchange(peer_public_key) once and obtains the identical shared secret. Next comes the step beginners most often skip and must not: the return value of exchange() is the raw output of the curve operation. Its byte distribution is not uniform and it is bound to no protocol context, so using it directly as an AES key is both non-standard and unsafe. The correct move is to feed the shared secret into the HKDF key-derivation function, binding the protocol name, both identities and other context into the info parameter, and derive a session key of proper length and uniform distribution. Context binding has a second benefit: the same key pair derives different keys in different protocols, preventing cross-protocol reuse.

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

alice_shared = alice_private.exchange(alice_peer)
bob_shared = bob_private.exchange(bob_peer)
assert alice_shared == bob_shared  # both sides computed the same secret

def derive(shared: bytes) -> bytes:
    return HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=None,
        info=b"pq-frontier demo session v1",  # bind the protocol context
    ).derive(shared)

alice_key = derive(alice_shared)
bob_key = derive(bob_shared)
assert alice_key == bob_key
print("session key agreed, length", len(alice_key))

Ephemeral keys and forward secrecy

Notice that in the code above both sides generate a brand-new key pair every time. That is not a casual demo habit; it is deliberate — these are ephemeral keys. The opposite is a static key pair, generated once and reused over a long period. The security consequences differ sharply. Suppose an attacker records all of your encrypted traffic today and, years later, somehow obtains your private key. With a static key, they can go back and open every recorded session — the retrospective risk known as “harvest now, decrypt later”. With a fresh ephemeral key pair per session, destroyed when the session ends, a later leak of your long-term identity key can only affect future sessions; every past session key became unrecoverable the moment its ephemeral private key was destroyed. That is forward secrecy, and it is why TLS 1.3 mandates ephemeral key exchange. As coding discipline it reduces to three rules: generate the key pair when the session starts, discard it when the session ends, and never write a session private key into a configuration file or database. The only key that needs long-term storage is the identity key used for signing, which is a separate line from session encryption — a distinction the next tutorial, on hybrid exchange, will meet again.

Why X25519, and not a curve you picked yourself

Beginners may ask: with so many elliptic curves available, why did the protocol world converge so one-sidedly on X25519? The answer lies not in mathematical taste but in engineering robustness. X25519’s design removes several famous implementation traps at the source: it uses the Montgomery ladder, which runs in naturally constant time without the developer tiptoeing around branches; it computes with the x-coordinate only, eliminating a whole class of point-validation checks; and private keys are clamped internally by the algorithm, so any 32 random bytes form a valid private key and the “generated an invalid key” corner case does not exist. By contrast, several older curves require implementers to handle on-curve point validation, twist-attack defences and branch constant-timeness themselves, and every one of those obligations has produced real vulnerabilities when neglected. The lesson generalizes across cryptographic engineering: prefer algorithms and interfaces where the correct approach is the default approach, and build security on design rather than on developer carefulness — which is also why this tutorial uses a mature library’s high-level interfaces throughout instead of hand-writing curve arithmetic.

From demo to production: three steps you cannot skip

First, check that the shared secret is not all zeros. If a peer maliciously sends a public key corresponding to a low-order point, exchange() can return an all-zero shared secret, meaning the exchange provided no security at all; the cryptography library raises an exception when it detects this case, but your protocol design should still be conscious of it rather than assuming a completed exchange means everything is fine. Second, key exchange alone says nothing about identity: the secret you computed is indeed known only to you and “whoever holds the matching private key”, but X25519 gives no guarantee that this person is who you think it is — a man in the middle can simply run one exchange with each side. Real protocols authenticate the public keys with signatures or pre-shared information; the certificate system in TLS exists precisely to close this gap. Third, perform key confirmation: each side computes a message authentication code over an agreed transcript with the derived key and sends it to the peer for verification, proving both parties really hold the same session key before any real data flows. With those three steps added, demo code starts to approach the production threshold; beyond that lies hybridizing X25519 with a post-quantum KEM — the subject of another tutorial.

Tags: PythonX25519HKDFcryptography