Diffie–Hellman

7 min read#cryptography

Two strangers agree on a shared secret over a fully public channel — the paint-mixing trick that launched public-key cryptography.

Contents

Diffie–Hellman

Diffie–Hellman key exchange solves a problem that sounds impossible: two people who have never met, shouting across a room full of eavesdroppers, end up holding the same secret number — and no listener can figure out what it is. Published in 1976 by Whitfield Diffie and Martin Hellman, it cracked open the field of Public-Key Cryptography.

It does not encrypt a message. It does something more fundamental: it lets Alice and Bob agree on a shared key over an open wire, which they can then feed into a fast symmetric cipher or a One-Time Pad.

The paint-mixing intuition

Forget numbers for a moment. Imagine mixing paint:

  1. Alice and Bob publicly agree on a common color — say yellow. Everyone, including the eavesdropper, sees it.
  2. Each secretly picks a private color and mixes it into the yellow. Alice makes one blend, Bob another. They swap these public blends in the open.
  3. Each stirs their own private color into the other's blend.

Both now hold yellow + Alice's secret + Bob's secret — the same mixture. The eavesdropper saw the two public blends but cannot un-mix paint to recover the private colors. Separating mixed paint is the "hard problem."

Alice and Bob each mix the shared base with a private tint, exchange the blends (the traveling dots), then mix in their own secret again. Both arrive at the identical shared color at center — the eavesdropper only ever saw the two public blends. Drag to change the private tints.

The math behind the paint

Replace paint with Modular Arithmetic and the trick becomes precise. Everyone agrees on a large prime p and a base g.

A = g^{a} \bmod p, \qquad B = g^{b} \bmod p
(1)

Alice keeps her secret exponent a private and sends A; Bob keeps b private and sends B. Now each raises what they received to their own secret:

\text{Alice computes } B^{a} = g^{ba} \bmod p, \qquad \text{Bob computes } A^{b} = g^{ab} \bmod p.

Since g^{ba} = g^{ab}, they hold the same value — the shared secret s = g^{ab} \bmod p. The exponents commute; that is the whole engine.

What it is and isn't

Diffie–Hellman gives you confidentiality of a freshly agreed key, but on its own it does not tell Alice who is really on the other end — a "man in the middle" could exchange keys with each side separately. Pinning down identity needs a Digital Signature or a trusted public key. In practice DH establishes the session key, and signatures vouch for who you are talking to.

An eavesdropper records p, g, A = g^a mod p and B = g^b mod p. Why can't they compute the shared secret g^(ab) mod p?

See also