Diffie-Hellman Key Exchange

How Ruby and Julia share a secret — even when someone is watching

Ruby and Julia each mix the common paint with their secret color to make a public color

Ruby and Julia each start with a common paint everyone can see. Then each secretly adds her own secret color — creating a unique public color.

The algorithm robot transports the public colors between Ruby and Julia

The algorithm transports the public colors between them.
* Assuming paint separation is expensive!

Ruby and Julia each add their secret color to the other person's public color

Now each adds her secret color to the other person's public color.
Public color + my secret = shared secret!

Ruby and Julia celebrate — they've both arrived at the same shared secret color

They both arrived at the same color!
Without ever sharing their secret paints.

· · ·

Try it yourself

Colors on the left, numbers on the right — same idea, two languages

1 Agree on a public starting point

🎨 Colors
Common Paint — click to change!
🔢 Numbers
Base (g):
Modulus (p):

2 Each picks a secret

🎨 Colors
Ruby
Secret
Julia
Secret
🔢 Numbers
Ruby
Secret (a):
Julia
Secret (b):

3 Combine public + secret = public value

🎨 Colors
Ruby
+ =
Julia
+ =
🔢 Numbers
Ruby
ga mod p = —
Julia
gb mod p = —
⇄

Public values are exchanged openly
(assuming paint separation is expensive!)

4 Add your secret to the other's public value

🎨 Colors
Ruby
+ =
Julia
+ =
🔢 Numbers
Ruby
Ba mod p = —
Julia
Ab mod p = —
🎨 Shared Secret Color
Ruby's
Julia's
🔢 Shared Secret Number
—
Ruby's
—
Julia's

They match!

Both arrive at the same secret — without ever sharing their private values.

🎨 Why it works with colors

Mixing paint is easy, but separating a mixed color back into its original paints is practically impossible. An eavesdropper sees the public colors but can't un-mix them.

🔢 Why it works with numbers

Computing ga mod p is fast, but figuring out a from the result (the "discrete logarithm") is extremely hard for large numbers.

Both sides get the same answer because:
(ga)b mod p = (gb)a mod p = gab mod p

The robot computing the math behind Diffie-Hellman