[python] Diffie Hellman key exchange demo…

Ok, I was studying my examination and I was directed to watch this video to understand how Diffie Hellman (DH) key exchange works mathematically, the video was really good, concise and easy to understand, so to add spice to my study (study for examination is the world’s most boring thing to do) I wrote a simple python script to derive secret keys for both Alice and Bob based on the video.

The result is printed in the python console:
Screenshot 2019-12-01 at 11.05.41 PM

This is the code in python. I am using the secrets module which is an built-in module of python.

from secrets import SystemRandom

# See video demonstration of DH key exchange
# in https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/v/diffie-hellman-key-exchange-part-2

# pseudo random number generator
prng = SystemRandom()

# g and p values agreed by both Alice and Bob.
g = prng.randint(1, 100)
p = prng.randint(1, 100)

print(f"Agreed g value:{g}, agreed modulo:{p}\n")

# Alice's private random number chose between 1 and 100
A = prng.randint(1, 100)
print(f"Alice's random number is {A}.\n")
# Bob's private random number chose between 1 and 100
B = prng.randint(1, 100)
print(f"Bob's random number is {B}.\n")

# public value of Alice's to be sent over to Bob.
a = g**A % p
print(f"Alice's calculated public value is {a}, which will be sent to Bob publicly.\n")

# public value of Bob's to be sent over to Alice.
b = g**B % p
print(f"Bob's calculated public value is {b}, which will be sent over to Alice publicly.\n")

# Alice uses Bob's public value and her private value to compute the secret key.
secret_key1 = b**A % p

# Bob uses Alice's public value and his private value to compute the secret key.
secret_key2 = a**B % p

if secret_key1 == secret_key2:
    print("Secret key has been successfully derived! See below...\n")
    print(f"Bob uses Alice's public value which is {a}, and his own private value which is {B}, "
          f"the secret key is {secret_key2}.\n")
    print(f"Alice uses Bob's public value which is {b}, and her own private random value which is {A},"
          f"the secret key is {secret_key1}.")
else:
    print("Alice and Bob have different secret keys, which is wrong! Try again!")
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s