Skip to content
Diffie-Hellman

Diffie-Hellman

The Diffie–Hellman key exchange is a method that generates a shared secret over a public channel. This method is based on the discrete logarithm problem which is believed to be hard to solve.

Key generation (Textbook DH)

Suppose a situation where Alice and Bob want to create a shared secret key. They will use a public channel to do so.

  1. They chose a standard prime number pp and a generator gg. gg is usually 2 or 5 to make computations easier. pp and gg are public and GF(p)=0,1,...,p1=g0modp,g1modp,...,gp1modpGF(p) = {0, 1, ..., p-1} = {g^0 \mod p, g^1 \mod p, ..., g^{p-1} \mod p} is a finite field.
  2. They create private keys aa and bb respectively. a,bGF(p)a, b \in GF(p).
  3. They compute the public keys AA and BB and send them over the public channel. A=gamodpA = g^a \mod p B=gbmodpB = g^b \mod p
  4. They can now both compute the shared secret key ss: Alice computes s=Bamodps = B^a \mod p and Bob computes s=Abmodps = A^b \mod p.
    s=Ba=Ab=gabmodps = B^a = A^b = g^{ab} \mod p

They can now use the shared secret ss to derive a symmetric key for AES for example, and use it to encrypt their messages.

Attacks

  • DH with weak prime using Pohlig–Hellman - Wikipedia

    The public prime modulus pp must be chosen such that p=2q+1p = 2*q + 1 where qq is also a prime. If p1p-1 is smooth (i.e have a lot of small, under 1000, factors), the Pohlig–Hellman algorithm can be used to compute the discrete logarithm very quickly. Sagemath’s discrete_log function can be used to compute the discrete logarithm for such primes.

    Use this script to generate smooth numbers of selected size.

  • Low-entropy secret with a partially smooth prime

    Even when p1p-1 is not fully smooth, Pohlig–Hellman still leaks the private key modulo the smooth part of p1p-1. This is enough to fully recover a low-entropy secret (for example a private key derived from a short password or hashed with a weak function).

    Write p1=NMp - 1 = N \cdot M where NN is the smooth part (product of the small prime factors) and MM is the rough cofactor. The map xxMx \mapsto x^M projects onto the unique subgroup H=gMH = \langle g^M \rangle of smooth order NN. With h:=gMh := g^M and y:=FMy := F^M, the public key F=gfF = g^f becomes y=hfy = h^f inside HH, so a discrete log in HH recovers

    fmodNf \bmod N

    If the secret satisfies f<Nf < N, this recovers ff entirely.

    from sage.all import *
    N = prod(P**e for P, e in factor(p-1) if P < 10**12)  # smooth part
    M = (p-1) // N
    f = discrete_log(Mod(F, p)**M, Mod(g, p)**M, ord=N)   # f mod N
  • DH with small prime

    The security of Diffie-Hellman is lower than the number of bits in pp. Consequently, is p is too small (for example 64bits), it is possible to compute the discrete logarithm in a reasonable amount of time.

    from sage.all import *
    a = discrete_log(Mod(A, p), Mod(g, p))