Python Notes: Diffie-Hellman (standalone demo)

  1. The information presented here is intended for educational use.
  2. The information presented here is provided free of charge, as-is, with no warranty of any kind.
  3. Edit: 2019-09-30

Python3 source code

#!/usr/bin/python3
# ------------------------------------------------------------
# Title  : dh10.py (this is the interactive version)
# Author : Neil Rieck
# created: 2019-08-31
# notes  :
# 1) Diffie-Hellman key-exchange demo
# 2) https://en.wikipedia.org/wiki/Diffie-Hellman_key_exchange
# ------------------------------------------------------------
#
import math
#
#   test if x is prime
#
def is_prime(n):
    if (((n % 2) == 0) and (n > 2)):
        return False
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        if n % i == 0:
            return False
    return True
#
#   get keyboard input (ensure it is an integer)
#
def prompt_for_int(msg,default):
    while True:
        try:
            myDefault=int(default)
            prompt = " "+msg +" (Default="+str(myDefault)+")? "
            userInput=input(prompt)
            if (userInput==""):
                userInput=myDefault
            userInput=int(userInput)
        except ValueError:
            print("not an integer")
            continue
        else:
            return userInput
#
# define default variables (p,g,a,b come from the algorithm)
# Note: these defaults came from the Wikipedia page
#
sharedPrime = 23    # p
sharedBase  = 5     # g
secretAlice = 4     # a
secretBob   = 3     # b
# =============================================
#    main
# =============================================
print("Diffie-Hellman Key Exchange Demo")
print("")
print("hint: primes between 3 and 999")
for I in range(3,1000):
    if (is_prime(I)==True):
        print(I,end=" ")
print("")
print("Publically shared data (first handshake)")
while True:
    sharedPrime=prompt_for_int("Publicly Shared Prime:", sharedPrime)
    if (is_prime(sharedPrime)==False):
        print("error: data entered is not a prime number")
        continue
    else:
        break; 
sharedBase =prompt_for_int("Publicly Shared Base :", sharedBase)
print("")
print("Private randomly generated data (never shared)")
secretAlice=prompt_for_int("Alice's secret number:", secretAlice)
secretBob  =prompt_for_int("Bob's secret number  :", secretBob)
print("")
print("computation step #1 (both side)")
print("handshake continues")
#
#   Alice Sends Bob: A = g^a mod p
#
A = (sharedBase**secretAlice) % sharedPrime
print( " Alice Sends This Over Public Channel: " , A )
# 
#   Bob Sends Alice: B = g^b mod p
#
B = (sharedBase ** secretBob) % sharedPrime
print( " Bob Sends   This Over Public Channel: ", B )
#
#   Private computation's begin
#
print("")
print("computation step #2 (both sides)")
print( "Privately Calculated Shared Secret:" )
# Alice Employs Bob's Shared Secret: s = B^a mod p
aliceSharedSecret = (B ** secretAlice) % sharedPrime
print( " Alice Computes Secret Key: ", aliceSharedSecret,"(symmetric key)")
 
# Bob Employs Alice's Shared Secret: s = A^b mod p
bobSharedSecret = (A**secretBob) % sharedPrime
print( " Bob   Computes Secret Key: ", bobSharedSecret,"(symmetric key)")
#
print("exit")

External Links


 Back to Home
 Neil Rieck
 Waterloo, Ontario, Canada.