Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

The Diffie-Hellman key exchange

By the end of this chapter, you'll be able to

  • Compute a modular power with pow in Python
  • Walk through a Diffie-Hellman key exchange between two people
  • Explain why a spy who sees the whole exchange cannot compute the secret
  • Describe the man-in-the-middle attack and how to protect against it

The idea with paint

Awa and Kofi agree out loud on a base colour: yellow. Each secretly chooses a colour of their own: red for Awa, blue for Kofi. Each mixes the yellow with their secret colour, and sends the mixture to the other, in front of everyone. Then each adds their own secret colour to the mixture received. Both get the same final colour: yellow + red + blue. The spy saw the yellow, the orange mixture and the green mixture, but separating a paint mixture is very hard: they do not get the final colour.

In mathematics, the "mixture that is easy to make and impossible to undo" is the modular power.

The modular power

pow(g, a, p) computes g to the power a, modulo p (the remainder of the division by p). Python computes it very fast, even for numbers with hundreds of digits. The reverse path, finding a from the result, is called the discrete logarithm: for large enough numbers, nobody knows how to do it in a reasonable time.

p, g = 23, 5                      # public numbers (tiny, for the example)
for a in range(1, 9):
    print(f"{g}^{a} mod {p} = {pow(g, a, p)}")
5^1 mod 23 = 5
5^2 mod 23 = 2
5^3 mod 23 = 10
5^4 mod 23 = 4
5^5 mod 23 = 20
5^6 mod 23 = 8
5^7 mod 23 = 17
5^8 mod 23 = 16

The results jump all over the place: knowing pow(5, a, 23) does not easily tell you what a is. With 23, you can try every value; with a 2,048-bit p (617 digits), it is out of reach.

The exchange, step by step

Both find the same value; the spy, who only saw 23, 5, 8 and 19, cannot compute it without solving a discrete logarithm.

Step 5 of 5
Text description of the animation
  1. Everyone knows these two numbers, the spy too.
  2. Each draws a secret number they tell nobody.
  3. They send each other A and B in front of everyone.
  4. Each raises the value received to their own secret.
  5. Both find the same value; the spy, who only saw 23, 5, 8 and 19, cannot compute it without solving a discrete logarithm.

Why does it work? Awa computes (g^b)^a and Kofi (g^a)^b: both equal g^(a×b) mod p. With real numbers:

import hashlib

# Public numbers. p = 2^127 - 1 is a known prime; in real life we use
# standardised groups of 2,048 bits or more, or elliptic curves (X25519).
p = 2**127 - 1
g = 3

a = 0x3F2A9C17B4E85D60A1C2E3F405162738   # Awa's secret  (for real: secrets.randbelow(p))
b = 0x51D2E3F4A5B6C7D8E9FA0B1C2D3E4F50   # Kofi's secret

A = pow(g, a, p)            # sent by Awa, in clear
B = pow(g, b, p)            # sent by Kofi, in clear

awa_secret = pow(B, a, p)
kofi_secret = pow(A, b, p)
print("identical:", awa_secret == kofi_secret)

# We don't encrypt with this number directly: we derive a 32-byte key from it.
key = hashlib.sha256(awa_secret.to_bytes(16, "big")).hexdigest()
print("derived key:", key[:32], "...")
identical: True
derived key: 42e6d00a65172c7e8156869556a53fa7 ...

The shared number is not used as it is: it goes through a key derivation function (here SHA-256, for real HKDF) to get an encryption key of the right size and well distributed. That is what your browser does at the start of every HTTPS connection, with the elliptic-curve version (X25519).

Mini-lab: the discrete logarithm quickly becomes impossiblePython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: one key for three

Awa, Kofi and Mei want a shared key. They want a single value g^(a×b×c) mod p known to all three. Show that it can be obtained by passing public values around, without ever revealing a, b or c. Use p = 2**127 - 1, g = 3 and the secrets a = 1111, b = 2222, c = 3333 (far too small for real use, but readable).

Hint 1
Awa publishes g^a. Kofi raises it to b and publishes g^(ab). What can Mei do with g^(ab)?
Hint 2
Three "rounds" are needed: each person must receive the product of the two other secrets, for example Mei receives g^(ab), Awa receives g^(bc) and Kofi receives g^(ca).
Show the solution and common mistakes
p, g = 2**127 - 1, 3
a, b, c = 1111, 2222, 3333          # secrets (too small for real use)

# Public values that are passed around:
ga, gb, gc = pow(g, a, p), pow(g, b, p), pow(g, c, p)
gab = pow(ga, b, p)                 # Kofi raises g^a to b
gbc = pow(gb, c, p)                 # Mei raises g^b to c
gca = pow(gc, a, p)                 # Awa raises g^c to a

mei_key = pow(gab, c, p)
awa_key = pow(gbc, a, p)
kofi_key = pow(gca, b, p)

print("the three keys are equal:", mei_key == awa_key == kofi_key)
print("equal to g^(abc):", mei_key == pow(g, a * b * c, p))
the three keys are equal: True
equal to g^(abc): True

Each person adds their secret to a value that already contains the two others. The public values (g^a, g^ab…) reveal no secret, for the same reason as in the two-party exchange. Group messaging apps today use more advanced protocols (such as MLS), which also handle members joining and leaving.

Common mistakes:

  • Multiplying the public values together (ga * gb): you get g^(a+b), not g^(ab).
  • Forgetting the third argument of pow: pow(g, a*b*c) without a modulus produces a gigantic number and freezes the program.
  • Using these small secrets for real: 1,111 is found in a few thousandths of a second by discrete logarithm.

Summary

  1. 1The modular power is easy to compute and very hard to reverse (discrete logarithm).
  2. 2In Diffie-Hellman, each person publishes g^secret and raises the value received to their own secret: both get g^(ab).
  3. 3An encryption key is then derived from the shared secret with a derivation function.
  4. 4Without authentication, a man in the middle can set up a key with each side and read everything: you must check who you are talking to.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.