Diffie-Hellman is used in key exchange. Bob and Alice agree on two values (g and p), where p is a prime number. Next Bob and Alice generate two random numbers (a and b), and exchange values:
Diffie-Hellman (Python) |
Method
The following outlines the method of Diffie-Hellman:
Sample code
The following gives some sample code for the DF calculation:
import random import base64 import hashlib import sys g=11 p=1001 x=random.randint(5, 10) y=random.randint(10,20) if (len(sys.argv)>1): g=int(sys.argv[1]) if (len(sys.argv)>2): p=int(sys.argv[2]) if (len(sys.argv)>3): x=int(sys.argv[3]) if (len(sys.argv)>4): y=int(sys.argv[4]) A=pow(g,x,p) B=pow(g,y,p) print ('g: ',g,' (a shared value), n: ',p, ' (a prime number)') print ('\nAlice calculates:') print ('a (Alice random): ',x) print ('Alice value (A): ',A,' (g^a) mod p') print ('\nBob calculates:') print ('b (Bob random): ',y) print ('Bob value (B): ',B,' (g^b) mod p') print ('\nAlice calculates:') keyA=pow(B,x, p) print ('Key: ',keyA,' (B^a) mod p') print ('Key: ',hashlib.sha256(keyA.to_bytes(32, byteorder = 'big')).hexdigest()) print ('\nBob calculates:') keyB=pow(A,y,p) print ('Key: ',keyB,' (A^b) mod p') print ('Key: ',hashlib.sha256(keyB.to_bytes(32, byteorder = 'big')).hexdigest())
In the end, we just convert our integer result into a byte array, and then hash it.