TExcelTAD
Home › Number Theory & Cryptography › Diffie-Hellman Key Exchange

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 (ga)b=(gb)a(g^a)^b = (g^b)^a 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 pp and a generator gg of a large prime-order subgroup (order qq).

  1. Alice picks a secret aa and sends A=ga mod pA = g^a \bmod p.
  2. Bob picks a secret bb and sends B=gb mod pB = g^b \bmod p.
  3. Alice computes K=BaK = B^a, Bob computes K=AbK = A^b. Both equal gabg^{ab}.

An eavesdropper sees p,g,A,Bp, g, A, B. Computing gabg^{ab} from them is the computational Diffie-Hellman problem, believed as hard as the discrete log.

python · try it yourself
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:

python · try it yourself
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.

python · try it yourself
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 aa and bb 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

Exercises

Exercise 1: By hand

With p=23p = 23, g=5g = 5, a=6a = 6, b=15b = 15, compute AA, BB and KK.

Answer

A=8A = 8, B=19B = 19, K=2K = 2.

Solution

52=25≡25^2 = 25 \equiv 2, so 56=23=85^6 = 2^3 = 8. 515=512⋅53=26⋅1255^{15} = 5^{12} \cdot 5^3 = 2^6 \cdot 125; 26=64≡182^6 = 64 \equiv 18 and 125≡10125 \equiv 10, so 515≡180≡195^{15} \equiv 180 \equiv 19. K=Ba=196K = B^a = 19^6: 19≡−419 \equiv -4, (−4)6=4096≡2(-4)^6 = 4096 \equiv 2 (4096=178⋅23+24096 = 178 \cdot 23 + 2). Check: Ab=815=245A^b = 8^{15} = 2^{45}; 211≡1(mod23)2^{11} \equiv 1 \pmod{23}, so 245=244⋅2≡22^{45} = 2^{44} \cdot 2 \equiv 2.

Exercise 2: Small subgroup

Why must Bob reject A=p−1A = p - 1?

Answer

p−1≡−1p - 1 \equiv -1 has order 2, so K=(−1)bK = (-1)^b is ±1\pm 1.

Solution

If an attacker substitutes A=−1A = -1, Bob's "secret" KK is 1 or p−1p - 1, which the attacker can guess, and the parity of bb 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 gabcg^{abc}. How many rounds of messages are needed?

Answer

Two rounds: pass ga,gb,gcg^a, g^b, g^c around, then gab,gbc,gcag^{ab}, g^{bc}, g^{ca}.

Solution
python · try it yourself
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…

  1. ga+bg^{a+b}
  2. gabg^{ab}
  3. abab
  4. A+BA + B

Unauthenticated Diffie-Hellman is vulnerable to…

  1. factoring
  2. a man-in-the-middle attack
  3. birthday attacks
  4. padding oracles

Forward secrecy means…

  1. keys are longer
  2. stealing a long-term key later does not expose past session keys
  3. messages arrive in order
  4. the server never stores data