Diffie-Hellman Key Exchange

Work in progress. This note is still being written and incomplete.

3 min read Last updated Sun Jul 05 2026 05:11:45 GMT+0000 (Coordinated Universal Time)

Diffie-Hellman (DH), invented in 1976 by Whitfield Diffie and Martin Hellman, lets 2 parties agree on a shared secret key using only publicly exchanged information. Security rests on the difficulty of computing discrete logarithms.

The protocol has 4 parts: define public parameters, generate key pairs, exchange public keys, compute the shared secret.

Public Parameters

  • A large prime modulus pp, defining the multiplicative group Zp\mathbb{Z}_p^*.
  • A generator gg, a primitive root modulo pp.

gg is a primitive root modulo pp iff every aa coprime to pp satisfies agi(modp)a \equiv g^i \pmod p for some integer ii, called the discrete logarithm of aa to base gg.

For prime pp, the p1p - 1 values i=1,,p1i = 1, \dots, p-1 generate {1,,p1}\{1, \dots, p-1\}, in some order, via gimodpg^i \bmod p.

Key Pair Generation

Each party chooses a secret integer and publishes its exponentiation modulo pp.

  • Alice chooses secret aZpa \in \mathbb{Z}_p^*, computes public Aga(modp)A \equiv g^a \pmod p.
  • Bob chooses secret bZpb \in \mathbb{Z}_p^*, computes public Bgb(modp)B \equiv g^b \pmod p.

Exchange of Public Keys

Public keys need no confidentiality, only authenticity and integrity, since a forged public key lets an attacker substitute their own key undetected.

Methods: a trusted public key server, in-person or verified exchange, or a CA-issued digital certificate.

Shared Secret Key

Alice computes k=Bamodp=gbamodpk = B^a \bmod p = g^{ba} \bmod p. Bob computes k=Abmodp=gabmodpk = A^b \bmod p = g^{ab} \bmod p. Both arrive at the same value since gabgba(modp)g^{ab} \equiv g^{ba} \pmod p.

Worked Example

p=23p = 23, g=5g = 5, a=6a = 6, b=15b = 15.

  • A=56mod23A = 5^6 \bmod 23.
  • B=515mod23B = 5^{15} \bmod 23.
  • Alice: k=B6mod23=2k = B^6 \bmod 23 = 2.
  • Bob: k=A15mod23=2k = A^{15} \bmod 23 = 2.

Man-in-the-Middle Attack

The basic DH protocol has no authentication of public keys, so it is vulnerable to a man-in-the-middle attack.

Mallory now holds a separate shared key with each party, and can decrypt, inspect, modify, or inject messages in the supposedly secure channel between Alice and Bob.

Was this helpful?