Skip to content
Optimal Lab

Security · interactive

Key exchange: Diffie-Hellman

Alice and Bob want a shared secret key, but everything they send can be read by Eve. Each picks a private number, sends a public one, and both end up with the same secret that never crossed the wire. Tiny numbers here so you can check the maths.

public: p = 23, g = 5

Alice

secret a = 6

A = 5^6 mod 23 = 8

B^a mod p = 2

Eve sees

p = 23, g = 5

A = 8, B = 19

not a, b, or the secret

Bob

secret b = 15

B = 5^15 mod 23 = 19

A^b mod p = 2

shared secret: 2 = 2

Eve could try every a until 5^a mod 23 = 8: she finds a = 6 in 6 tries. With a 2048-bit p that search takes longer than the age of the universe.

Both compute g^(ab) mod p = 2: Alice as (g^b)^a, Bob as (g^a)^b. Eve only has g^a and g^b, and multiplying those gives g^(a+b), not g^(ab).

  1. 1

  2. 2

  3. 3

    Each raises the other's public value to their own secret. The results match; derive the session key from it.

    (g^b)^a = (g^a)^b

  4. 4

In production

Tools and technologies

Every TLS connection starts with a key exchange.

Not tied to one language — use these names when you search docs or design a system.