Diffie-Hellman Key Exchange
In 1976 Diffie and Hellman showed that two parties who have never met can agree on a shared secret over a channel that everyone can read. The trick is the commutativity together with the hardness of discrete logarithms. Every TLS 1.3 handshake still performs a Diffie-Hellman exchange, usually on an elliptic curve.
The protocol
Public parameters: a prime and a generator of a large prime-order subgroup (order ).
- Alice picks a secret and sends .
- Bob picks a secret and sends .
- Alice computes , Bob computes . Both equal .
An eavesdropper sees . Computing from them is the computational Diffie-Hellman problem, believed as hard as the discrete log.
import hashlib
# A toy safe-prime group: p = 2q + 1 with q = 1013 prime;
# g = 4 = 2^2 generates the subgroup of prime order q
p, q, g = 2027, 1013, 4
a, b = 777, 345 # secret exponents (normally drawn with secrets.randbelow)
A, B = pow(g, a, p), pow(g, b, p)
K_alice, K_bob = pow(B, a, p), pow(A, b, p)
print("public:", A, B, " shared:", K_alice, K_bob)
key = hashlib.sha256(K_alice.to_bytes(2, "big")).hexdigest()
print("derived key:", key[:32])public: 1634 907 shared: 283 283
derived key: 145bfb83f7b3ef33ac1eada788c187e4
The raw shared value is not used directly as a key: it is passed through a key derivation function (HKDF in TLS) so the key is uniformly random bits.
A realistic group size
Production finite-field DH uses fixed, published safe primes of 2048 to 8192 bits (RFC 7919's ffdhe groups). The arithmetic is identical; only the numbers are larger:
from sympy import isprime
# Build a 256-bit safe prime deterministically (search from a fixed start), then do DH in it.
q = 2**255 + 95
while not (isprime(q) and isprime(2 * q + 1)):
q += 2
p = 2 * q + 1
g = 4 # a square, so it lies in the order-q subgroup
a = 0x6D1F_A3C2_9B04_77E5_1C88_D2F0_4B6A_9E13_57C0_2BD4_8E61_F9A5_3C07_D218_6B4F_E931 % q
b = 0x2A7C_E519_0D84_B3F6_6E02_9A1D_C745_83BF_10E6_5D9C_42A8_F073_B91E_6C25_D840_7F1A % q
A, B = pow(g, a, p), pow(g, b, p)
print(p.bit_length(), "bit safe prime;", "secrets agree:", pow(B, a, p) == pow(A, b, p))
print("A is in the subgroup:", pow(A, q, p) == 1)257 bit safe prime; secrets agree: True
A is in the subgroup: True
Man in the middle
Plain Diffie-Hellman authenticates no one. Mallory, sitting between Alice and Bob, runs one exchange with each of them and relays traffic, reading everything.
p, g = 2027, 4
a, b, m1, m2 = 777, 345, 111, 222 # m1, m2: Mallory's secrets
A, B = pow(g, a, p), pow(g, b, p)
M1, M2 = pow(g, m1, p), pow(g, m2, p)
# Mallory replaces A by M1 (towards Bob) and B by M2 (towards Alice)
K_alice = pow(M2, a, p); K_bob = pow(M1, b, p)
print("Alice's key:", K_alice, " Mallory has it:", pow(A, m2, p))
print("Bob's key: ", K_bob, " Mallory has it:", pow(B, m1, p))Alice's key: 144 Mallory has it: 144
Bob's key: 171 Mallory has it: 171
The fix is authentication: sign the exchanged values with long-term keys (TLS server certificates, SSH host keys) or use a pre-shared secret.
Ephemeral keys and forward secrecy
If and are fresh random numbers for every session and erased afterwards ("ephemeral" DH, DHE/ECDHE), stealing a server's long-term key later does not decrypt recorded past sessions. RSA key transport lacked this property, which is a main reason TLS 1.3 dropped it.
In software
- TLS 1.3 offers
ffdhe2048toffdhe8192and, far more often, X25519 and P-256 (Elliptic-Curve Diffie-Hellman). - Implementations must validate peer values: reject and check subgroup membership (Pohlig-Hellman and Safe Primes). How TLS uses the result: TLS.
Exercises
Exercise 1: By hand
With , , , , compute , and .
Answer
, , .
Solution
, so . ; and , so . : , (). Check: ; , so .
Exercise 2: Small subgroup
Why must Bob reject ?
Answer
has order 2, so is .
Solution
If an attacker substitutes , Bob's "secret" is 1 or , which the attacker can guess, and the parity of leaks. Values of order 1 or 2 must be rejected; in a safe-prime group those are the only small subgroups.
Exercise 3: Three parties (code)
Extend DH to three people Alice, Bob and Carol so that all end with . How many rounds of messages are needed?
Answer
Two rounds: pass around, then .
Solution
p, g = 2027, 4
a, b, c = 101, 202, 303
r1 = {"A->B": pow(g, a, p), "B->C": pow(g, b, p), "C->A": pow(g, c, p)}
r2 = {"B->C": pow(r1["A->B"], b, p), "C->A": pow(r1["B->C"], c, p), "A->B": pow(r1["C->A"], a, p)}
keys = (pow(r2["C->A"], a, p), pow(r2["A->B"], b, p), pow(r2["B->C"], c, p))
print(keys, pow(g, a * b * c, p))(1947, 1947, 1947) 1947
Go further: Diffie–Hellman and the Man in the Middle has a step-by-step lab with a brute-force discrete log and Mallory's attack.
Test yourself
In Diffie-Hellman, the shared secret is…
Unauthenticated Diffie-Hellman is vulnerable to…
- factoring
- a man-in-the-middle attack
- birthday attacks
- padding oracles
Forward secrecy means…
- keys are longer
- stealing a long-term key later does not expose past session keys
- messages arrive in order
- the server never stores data