Diffie–Hellman & Elliptic Curves
Agreeing on a secret over a public channel — the Diffie–Hellman key exchange, the colour-mixing analogy, discrete logarithms, ephemeral keys and forward secrecy, elliptic-curve cryptography (point addition, scalar multiplication), Curve25519, P-256 and ECDSA/EdDSA, and pitfalls.
How can two people who have never met agree on a secret key while an eavesdropper hears every word they say? Diffie–Hellman key exchange (1976) answers this — it's the foundation of TLS, SSH, Signal, WireGuard and VPNs.
The colour-mixing analogy
- Alice and Bob publicly agree on a common colour: yellow.
- Each picks a secret colour: Alice red, Bob blue.
- Each mixes their secret with yellow and sends the mixture publicly: Alice sends orange; Bob sends green.
- Each adds their own secret to what they received: Alice mixes red into green; Bob mixes blue into orange. Both get the same brown.
An eavesdropper sees yellow, orange and green — but "un-mixing" paint to recover red or blue is hard. The mathematical version of hard-to-unmix is the discrete logarithm.
Finite-field Diffie–Hellman
Public parameters: a large prime p and a generator g.
| Alice | Public channel | Bob |
|---|---|---|
| Secret random a | Secret random b | |
| A → , ← B | ||
Both compute . The eavesdropper knows g, p, and , but computing (the computational Diffie–Hellman problem) or recovering a from (the discrete logarithm problem) is infeasible for well-chosen 2048+ bit p.
import secrets
p = 2**127 - 1 # a prime, fine for a demo — real deployments use 2048+ bit standard groups (RFC 7919) or X25519
g = 3
a = secrets.randbelow(p - 2) + 1; A = pow(g, a, p) # Alice
b = secrets.randbelow(p - 2) + 1; B = pow(g, b, p) # Bob
assert pow(B, a, p) == pow(A, b, p) # same shared secretThe raw shared secret is then fed through a key derivation function (HKDF) to produce the actual symmetric keys.
DH alone doesn't authenticate
Plain Diffie–Hellman is vulnerable to a man in the middle: Mallory runs one exchange with Alice and another with Bob and relays traffic between them. Real protocols authenticate the exchange — in TLS, the server signs its DH share with the key in its certificate (PKI and certificates); Signal uses identity keys verified via safety numbers.
Forward secrecy
If you encrypt session keys with a server's long-term RSA key, an attacker who records traffic today and steals that key years later can decrypt everything.
With ephemeral Diffie–Hellman (DHE/ECDHE), each session uses fresh, random DH key pairs that are discarded afterwards. The long-term key only signs the exchange. Stealing it later doesn't reveal past session keys — forward secrecy (perfect forward secrecy). TLS 1.3 requires ephemeral key exchange. Signal's double ratchet goes further, deriving a new key for every message.
Elliptic-curve cryptography
An elliptic curve over a finite field is the set of points (x, y) satisfying an equation like , plus a "point at infinity". Points can be added with a geometric rule (draw a line through two points; it meets the curve at a third; reflect it).
- Scalar multiplication (k times) is fast via double-and-add — O(log k) steps.
- Recovering k from — the elliptic-curve discrete logarithm problem (ECDLP) — is believed much harder than discrete logs modulo a prime, so the best attacks are generic, ~ steps.
Result: a 256-bit elliptic-curve key gives about the same security as a 3072-bit RSA or DH key — smaller keys, faster operations, less bandwidth.
ECDH
Exactly Diffie–Hellman, using point multiplication instead of exponentiation:
| Alice | Bob |
|---|---|
| Secret scalar a, public | Secret b, public |
| Shared | Shared |
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
alice, bob = X25519PrivateKey.generate(), X25519PrivateKey.generate()
s1 = alice.exchange(bob.public_key())
s2 = bob.exchange(alice.public_key())
assert s1 == s2 # 32-byte shared secret
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b"chat v1 session").derive(s1)Curves in practice
| Curve | Notes |
|---|---|
| Curve25519 / X25519 (key exchange), Ed25519 (signatures) | Designed by Bernstein for speed and safety: constant-time by design, no special cases to get wrong; default in TLS 1.3, SSH, Signal, WireGuard |
| NIST P-256 (secp256r1) | Widely deployed (TLS, WebAuthn/passkeys, smart cards); requires careful implementation |
| P-384, P-521 | Higher security levels (government use) |
| secp256k1 | Bitcoin and Ethereum signatures |
Signatures on curves: ECDSA (P-256, secp256k1) and EdDSA/Ed25519 (Digital signatures).
Pitfalls
- Invalid-curve attacks: if an implementation doesn't check that a received point lies on the correct curve, an attacker can send points on weaker curves and learn the private key bit by bit. X25519's design makes this a non-issue; for other curves, validate points.
- Small-subgroup attacks on finite-field DH: validate public values; use standard safe groups.
- Weak parameters: export-grade 512-bit DH enabled the Logjam attack (2015); a few widely shared 1024-bit primes are within reach of nation-state precomputation. Use ≥ 2048-bit standard groups or, better, X25519.
- Using the raw shared secret as a key — always run it through a KDF with context.
- Unauthenticated exchange → man in the middle.
- Quantum computers break both DH and ECDH; modern deployments use hybrid X25519 + ML-KEM (Public-key cryptography).
- Diffie–Hellman lets two parties derive a shared secret over a public channel; security rests on the discrete logarithm problem.
- Raw DH must be authenticated (signatures, certificates) to stop man-in-the-middle attacks.
- Ephemeral key exchange gives forward secrecy: stolen long-term keys don't decrypt past sessions; TLS 1.3 requires it.
- Elliptic curves give equivalent security with much smaller keys (256-bit ECC ≈ 3072-bit RSA).
- X25519/Ed25519 are fast, misuse-resistant defaults; P-256 is widely deployed.
- Validate inputs, use standard parameters, derive keys with a KDF, and plan for post-quantum hybrids.