The Math


Public Parameters

Alice and Bob first agree on two public numbers:

  • p: a large prime number
  • g: a generator (a number with special properties)

Everyone can know these. They’re not secret.


Let’s Use Real Numbers

ParameterValue
Prime pp23
Generator gg5

Alice’s Side

Step 1: Alice picks a secret number.

a=6a = 6

This is her private key. She never shares it.


Step 2: Alice computes her public value.

A=gamodpA = g^a \mod p

A=56mod23\phantom{A} = 5^6 \mod 23

A=15625mod23\phantom{A} = 15625 \mod 23

A=8\phantom{A} = 8

She sends A = 8 to Bob. Everyone can see this.


Bob’s Side

Step 1: Bob picks a secret number.

b=15b = 15

This is his private key. He never shares it.


Step 2: Bob computes his public value.

B=gbmodpB = g^b \mod p

B=515mod23\phantom{B} = 5^{15} \mod 23

B=19\phantom{B} = 19

He sends B = 19 to Alice. Everyone can see this.


Creating the Shared Secret

Now comes the magic.


Alice computes:

K=BamodpK = B^a \mod p

K=196mod23\phantom{K} = 19^6 \mod 23

K=2\phantom{K} = 2


Bob computes:

K=AbmodpK = A^b \mod p

K=815mod23\phantom{K} = 8^{15} \mod 23

K=2\phantom{K} = 2


Same answer! Both get K = 2.

This is their shared secret. They can now use it as a key for symmetric encryption.


Why Do They Get the Same Answer?

Alice computes: Ba=(gb)a=gbaB^a = (g^b)^a = g^{ba}

Bob computes: Ab=(ga)b=gabA^b = (g^a)^b = g^{ab}

Since ab=baab = ba, they get the same result.


What Eve (the Attacker) Sees

Eve is watching the whole conversation. She knows:

ValueKnown to Eve?
p=23p = 23Yes (public)
g=5g = 5Yes (public)
A=8A = 8Yes (sent publicly)
B=19B = 19Yes (sent publicly)
a=6a = 6No (Alice’s secret)
b=15b = 15No (Bob’s secret)
K=2K = 2No (shared secret)

Why Can’t Eve Calculate K?

To find K, Eve would need either aa or bb.

She knows A=8A = 8 and that A=5amod23A = 5^a \mod 23.

So she needs to find aa where 5amod23=85^a \mod 23 = 8.


This is the Discrete Logarithm Problem.

For small numbers like 23, she could just try all possibilities. But for a 600-digit prime? There’s no known efficient algorithm.

Diffie-Hellman’s security rests on the difficulty of the discrete logarithm problem.