Cryptography / Diffie–Hellman key exchange

Diffie–Hellman key exchange

Two people who have never met agree on a secret number while shouting across a crowded room. Seven steps, one prime, no shared password.

Beginner7 steps~6 min
Alice — holds private a
Bob — holds private b
Eve — hears p, g, A and B
// THE SHORT VERSION

In 30 seconds

Diffie–Hellman lets two people agree on a secret number over a line anyone can listen to.

Each picks a private number, mixes it with a shared public base, and sends the result. Each then mixes what they received with their own private number, and both arrive at the same value.

An eavesdropper sees both mixed values but cannot un-mix them: that is the discrete logarithm problem, and no fast method for it is known.

Diffie–Hellman key exchange, step by step

STEPS01 / 07

Toy numbers keep the math visible. Real Diffie–Hellman uses primes of 2048 bits or more, or elliptic curves.

STEP 01 / 07 Agree in public
THE MATH
p = 23 (a prime) g = 5 (a generator)
  1. Step 1: Agree in public. Alice and Bob start by agreeing, out loud, on a prime p and a base g. Eve hears both. That is fine — nothing secret has been said yet.
  2. Step 2: Mix paint (the analogy). Picture paint. Each side stirs a secret colour into a common one and swaps the result. Adding your own secret again gives both the same final colour — and un-mixing paint is hard.
  3. Step 3: Alice picks a secret. Alice picks a private number a = 6 and computes A = 5⁶ mod 23. That is her “public mix”: safe to send, because going from 8 back to 6 is the hard direction.
  4. Step 4: Bob picks a secret. Bob does the same with his own private b = 15. He never learns Alice’s a, and she never learns his b.
  5. Step 5: Swap the mixes. A and B cross the open line. Eve now holds p, g, A and B — every number that was ever sent.
  6. Step 6: Both reach the same s. Alice raises Bob’s B to her a; Bob raises Alice’s A to his b. Both are really computing 5⁶ˣ¹⁵ mod 23, so they land on the same s = 2 — a key that never crossed the wire.
  7. Step 7: Eve’s hard problem. To get s, Eve must recover a from A — the discrete logarithm. With p = 23 she simply tries every exponent. With a 2048-bit prime there are too many to try, and no fast method is known.
VALUES SO FAR
p23public
g5public
a····secret
A····public
b····secret
B····public
s····secret
// BEFORE

Learn this first

Nothing. This concept starts from scratch.

Spotted a mistake on this page?