Diffie-Hellman key exchange

Introduction

DH, the Diffie-Hellman key exchange, is a protocol that lets two sides who have never met agree on a shared secret key while talking over a channel that everyone can read. Whitfield Diffie and Martin Hellman published it in 1976 in the paper "New Directions in Cryptography", and it solved the main problem of classical cryptography, the distribution of keys. Ralph Merkle also worked on the idea, and some texts call the protocol Diffie-Hellman-Merkle.

DH does not encrypt anything by itself. The shared secret that comes out of it is used as the key of a symmetric cipher for the rest of the conversation. You meet it in HTTPS (TLS) and in SSH.

The idea

The protocol rests on an operation that is easy to do and very hard to undo: raising a number to a power modulo a prime p is fast, but finding the power from the result (the discrete logarithm problem) is not.

  1. Alice and Bob agree on the public numbers: a prime p and a base g. An eavesdropper may know them.
  2. Alice picks a secret number a and sends Bob A = ga mod p.
  3. Bob picks a secret number b and sends Alice B = gb mod p.
  4. Alice computes Ba mod p, Bob computes Ab mod p.

Both get the same number, because (gb)a = (ga)b = gab mod p. The secrets a and b never cross the wire.

Example with small numbers

Let p = 23 and g = 5. Alice chooses a = 6, Bob chooses b = 15.

StepAliceBob
Secreta = 6b = 15
SendsA = 56 mod 23 = 8B = 515 mod 23 = 19
Computes196 mod 23 = 2815 mod 23 = 2

You can check it with the three-argument pow of Python, which computes the power modulo a number:

python3 -c "p,g,a,b=23,5,6,15; A=pow(g,a,p); B=pow(g,b,p); print(A, B, pow(B,a,p), pow(A,b,p))"

8 19 2 2

The four numbers are A, B and the secret that Alice and Bob each computed.

Why an eavesdropper cannot repeat it

The eavesdropper sees p, g, A and B. To get the secret they need a or b, which means solving the discrete logarithm. With p = 23 they would try all the powers in a second. Real parameters use a prime of at least 2048 bits, and for such numbers no efficient method is known.

The weak point: no authentication

DH proves nothing about who is on the other end. An attacker who sits in the middle can run one exchange with Alice and another with Bob, and read and pass on everything: this is the man-in-the-middle attack. So in practice the exchange is signed: in TLS the server signs its DH value with the key of its certificate (see PKI), and the client checks the signature.

Diffie-Hellman today

Article author: Andrei Olegovich