Diffie Hellman Example with Python

Published
Reading time1 min

Introduction

Diffie Hellman key exchange is a method of constructing a shared secret between two parties. A shared secret is something that can be used as a key to conduct symmetric encryption, such as AES. The Diffie Hellman key exchange depends on the difficulty of the discrete log problem, which is generally believed to be hard in this current day and age. Understanding this usually requires some understanding of mathematical groups.

Discrete Log Problem

This discrete log problem is the issue of finding the exponent needed to raise some number bb to yield some other number aa, within some group GG. For this post, we will assume the group to be the integers modulus pp, or Zp\mathbb{Z}_p, and the group operation to be multiplication modulo pp. pp should be a prime number to ensure the generator gg cycles over the entire domain of Zp\mathbb{Z}_p.

This is finding kk in the following equation, a=bka=b^k, where aa and bb are given, and mod  p\mod p is implied.

Diffie Hellman Key Exchange

Let there be a public generator g=2g=2 of some group G=Z41G=\mathbb{Z}_{41}, with associated p=41p=41.

>>> g = 2
>>> p = 41
>>> a = 6
>>> pow(g,a,p)
23

Alice generates some secret value a=6a=6, computes ga=23g^a=23, and sends this to Bob. Notice because the discrete log problem is hard (aa and pp are sufficiently large to prevent a brute force attack), some eavesdropper is unable to find aa given gag^a.

>>> g = 2
>>> p = 41
>>> b = 5
>>> pow(g,a,p)
32

Bob does the same for secret value b=5b=5, sending gb=32g^b=32 to Alice. Notice an eavesdropper cannot compute bb from the public value gbg^b.

Alice and Bob can then generate shared secret gabg^{ab}.

# Alice computing g^(ab)
>>> g_b = 32
>>> a = 6
>>> pow(g_b, a, p)
40
# Bob computing g^(ab)
>>> g_a = 23
>>> b = 5
>>> pow(g_a, b, p)
40

gab=40g^{ab}=40, which is now a shared secret. This shared secret could be used as a key, or as a seed for a pseudo random number generator to generate many keys for transmitting data with a stream cipher.

Sources

Great video on the Diffie Hellman key exchange