Algorithms · Safety nets

Diffie–Hellman key exchange

How WhatsApp agrees on a secret in public. Two phones shout numbers across the internet and end up with a secret nobody else can work out.

The problem

You send a message to a friend. It hops through cables, Wi-Fi routers and servers you will never see. To keep it private, you and your friend need to scramble it with a shared secret key, and nobody else may know that key.

Here is the catch. You have never met in person, so the only way to agree on the key is to talk over that same watched channel. In 2016, WhatsApp announced it had finished rolling out end-to-end encryption using the Signal Protocol, and solving this puzzle is the heart of it.

The obvious way

Just send the key: "Hi, our password is 77." Anyone listening on the wire now knows 77 too, and can unscramble every message you ever send. The secret was exposed at the exact moment you shared it, so the scrambling protects nothing.

The clever idea

Picture mixing paint. You and a friend publicly agree on a shared yellow. Each of you secretly picks a private color and mixes it in, then you swap the mixed buckets in public. Each of you adds your own private color to the other's bucket. You both end up with the same final shade, and a spy holding only the swapped buckets cannot un-mix them.

That is Diffie–Hellman key agreement (1976). Each side keeps a private number and sends a public value computed from it. Both then compute the same shared secret. Real Signal uses an elliptic-curve version called X25519, but the toy below shows the same shape.

How the code does it

The obvious way, lines 9–11, is a dead end: whatever crosses the wire is the key. The clever way starts at the exchange. pow(g, a, p) means "g to the power a, then keep only the remainder after dividing by p". Alice sends A, Bob sends B, and each raises the other's value to their own private number to land on the same secret.

Eve's only move is brute force. With a tiny prime she finds the private number quickly. Look at the growth loop: the bars climb steeply as the prime gets bigger, because each extra bit roughly doubles her tries. Then the XOR step shows the secret doing its job, scrambling and unscrambling a message.

Trade-offs

Key agreement costs real computation, and the toy numbers here are breakable, which is why real ones are huge. It also proves nothing about who you are talking to, so you still need a way to verify identity. Signal adds ratchets that keep changing the keys, so one stolen key doesn't expose everything. Don't use hand-rolled code like this for real secrets.

Where else you’ll see it

Variants of this idea set up secure connections all over the internet. To see the production-grade version, with X25519 and the ratchets, browse the open-source Signal library at github.com/signalapp/libsignal.

Eve's tries roughly double for each extra bit in p. What happens when p grows from 14 bits to 24 bits?

  • About 10 more tries
  • Roughly 1000 times more tries
  • No change
Show the answer

Roughly 1000 times more tries. Ten extra bits means doubling ten times, which is 2^10 = 1024 times more work for Eve.

Change it and see
  • Change 10007 to 1019 and rerun
  • Change Alice's 3001 to 500
  • Change the message text
  • Add 100003 to the prime list

The code

Python, with what each line means beside it. It compares the clever way with sending the password itself.

def crack(g, A, p):Define Eve's guessing helper
for tries in range(1, p):Try each exponent from 1 upward
if pow(g, tries, p) == A:If g to that power matches the public value
return triesReturn how many tries it took
def xor(text, key):Define a simple scrambler
return "".join(chr(ord(c) ^ key) for c in text)Flip every character's bits using the key
# Obvious way: the key itself travels the wire
key = 77Obvious way: send the key itself
show({"Eve sees": key, "Eve needs": key}, "Obvious way: Eve already has it")Show that Eve sees exactly what she needs
# Clever way: Diffie-Hellman
p, g = 10007, 5Pick a public prime and generator
a, b = 3001, 4242Alice and Bob each pick private numbers
A, B = pow(g, a, p), pow(g, b, p)Each computes a public value to send
alice, bob = pow(B, a, p), pow(A, b, p)Each combines the other's public value with their own
show({"Alice": alice, "Bob": bob, "Eve sees": f"{A}, {B}"}, "Clever way: same secret, never sent")Show both secrets match, Eve sees only publics
secret = alice % 255 + 1Turn the shared secret into a small key
scrambled = xor("meet at 9", secret)Scramble a short message with it
print("On the wire:", repr(scrambled))Show the garbled text on the wire
print("Bob reads:", xor(scrambled, bob % 255 + 1))Bob unscrambles it with his own secret
costs = []Start a list of Eve's costs
for prime in [23, 107, 1019, 10007]:For each bigger prime
costs.append(crack(g, pow(g, prime // 3, prime), prime))Eve brute-forces the public value, counting tries
show(costs, "Eve's tries for 5, 7, 10, 14-bit primes")Show tries as bars
print("Tries:", costs)Print the raw counts

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on safety nets