Saturday, August 8, 2020

Simple Diffie–Hellman Key Exchange Example in Python.

Diffie-Hellman Key Exchange Method

DiffieHellman key exchange method allows two parties that have no prior knowledge of each other to jointly establish a shared secret key over an insecure channel. This key can then be used to encrypt subsequent communications using a symmetric key cipher.


EXAMPLE :-



import random
global prime, root

def secretnumber ():
secret = int(random.randint(0,100))
return secret

print ("Alice And Bob Agree The Prime :")
prime = 23
print ("The Prime is : ",prime, "\n")

print ("Alice and Bob Agree The Primitive Root to use")
root = 5
print ("The Root is :",root, "\n")

print ("At This Stage, Alice, Bob & Eve All Know the Prime and the Root", "\n")

alicesecret = secretnumber()
print ("Alice chooses a secret Number :",alicesecret)

bobsecret = secretnumber()
print ("Bob Chooses a secret Number :", bobsecret, "\n")

print ("Alice calculates her public key as A = root ^ alicesecret mod Prime :")
alicepublic = (root ** alicesecret) % prime
print ("Alice's public key is :",alicepublic, "\n")

print ("Bob calculates his public key as B = root ^ bobsecret mod prime :")
bobpublic = (root ** bobsecret) % prime
print ("Bob's public key is :", bobpublic, "\n")

print ("Alice and Bob exchange their public keys :")
print ("Eve now knows Alice and Bob's public keys :", "\n")

print ("Alice calculates the shared key as K = B ^ alicesecret mod prime :")
alicekey = (bobpublic ** alicesecret) % prime

print ("Bob calculates the shared key as K = A ^ bobsecret mod prime :")
bobkey = (alicepublic ** bobsecret) % prime
print ("Alice calculates the shared key and gets :", alicekey)
print ("Bob calculates the shared key and gets :", bobkey, "\n")

print ("Eve does not know the shared private key that Alice & Bob can now use :")
print ("Poor Eve :(", "\n")






OUTPUT

Alice And Bob Agree The Prime :
The Prime is :  23 

Alice and Bob Agree The Primitive Root to use
The Root is : 5 

At This Stage, Alice, Bob & Eve All Know the Prime and the Root 

Alice chooses a secret Number : 74
Bob Chooses a secret Number : 46 

Alice calculates her public key as A = root ^ alicesecret mod Prime :
Alice's public key is : 16 

Bob calculates his public key as B = root ^ bobsecret mod prime :
Bob's public key is : 2 

Alice and Bob exchange their public keys :
Eve now knows Alice and Bob's public keys : 

Alice calculates the shared key as K = B ^ alicesecret mod prime :
Bob calculates the shared key as K = A ^ bobsecret mod prime :
Alice calculates the shared key and gets : 3
Bob calculates the shared key and gets : 3 

Eve does not know the shared private key that Alice & Bob can now use :
Poor Eve :( 




No comments:

Post a Comment

Please do not any spam link in Comment Box