Lesson 7 of 15

Diffie-Hellman Key Exchange

Diffie-Hellman Key Exchange

Published by Whitfield Diffie and Martin Hellman in 1976, the Diffie-Hellman key exchange was the first practical public-key protocol. It allows two parties to establish a shared secret over an insecure channel without ever sending the secret itself.

The Protocol

Both parties agree on public parameters: a prime pp and a generator gg (a primitive root modulo pp).

  1. Alice picks a private key aa, computes public key A=gamodpA = g^a \bmod p
  2. Bob picks a private key bb, computes public key B=gbmodpB = g^b \bmod p
  3. Alice and Bob exchange AA and BB publicly
  4. Alice computes s=Bamodp=gabmodps = B^a \bmod p = g^{ab} \bmod p
  5. Bob computes s=Abmodp=gabmodps = A^b \bmod p = g^{ab} \bmod p

Both arrive at the same shared secret s=gabmodps = g^{ab} \bmod p.

Why It's Secure

An eavesdropper sees gg, pp, A=gamodpA = g^a \bmod p, and B=gbmodpB = g^b \bmod p, but cannot compute gabmodpg^{ab} \bmod p without solving the Discrete Logarithm Problem — finding aa from gamodpg^a \bmod p. This is believed to be computationally hard for large pp.

Classic Example

g=2g = 2, p=23p = 23 (a prime), a=6a = 6, b=15b = 15:

PartyPrivatePublic
Alicea=6a = 6A=26mod23=18A = 2^6 \bmod 23 = 18
Bobb=15b = 15B=215mod23=16B = 2^{15} \bmod 23 = 16

Shared secret: Bamod23=166mod23=4=Abmod23B^a \bmod 23 = 16^6 \bmod 23 = 4 = A^b \bmod 23.

Your Task

Implement:

  • dh_public_key(g, private_key, p) — compute gprivate_keymodpg^{\text{private\_key}} \bmod p
  • dh_shared_secret(other_public, private_key, p) — compute other_publicprivate_keymodp\text{other\_public}^{\text{private\_key}} \bmod p
Python runtime loading...
Loading...
Click "Run" to execute your code.