Diffie Hellman Example with Python
| Published | |
|---|---|
| Reading time | 1 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 to yield some other number , within some group . For this post, we will assume the group to be the integers modulus , or , and the group operation to be multiplication modulo . should be a prime number to ensure the generator cycles over the entire domain of .
This is finding in the following equation, , where and are given, and is implied.
Diffie Hellman Key Exchange
Let there be a public generator of some group , with associated .
>>> g = 2
>>> p = 41
>>> a = 6
>>> pow(g,a,p)
23
Alice generates some secret value , computes , and sends this to Bob. Notice because the discrete log problem is hard ( and are sufficiently large to prevent a brute force attack), some eavesdropper is unable to find given .
>>> g = 2
>>> p = 41
>>> b = 5
>>> pow(g,a,p)
32
Bob does the same for secret value , sending to Alice. Notice an eavesdropper cannot compute from the public value .
Alice and Bob can then generate shared secret .
# 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
, 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.