This post is about Diffie-Hellman exchange key protocol to be used for symmetric crypto protocol like AES. From Wiki:
Diffie–Hellman key exchange[nb 1] is a method of securely exchanging cryptographic keys over a public channel and was one of the first public-key protocols as conceived by Ralph Merkle and named after Whitfield Diffie and Martin Hellman.
Same as RSA, i am not going to go through the math, but the algorithm defines how Alice and Bob create the their keys and eventually create the common key.
import random
class DH():
def __init__(self, p, alfa):
self.p = p
self.alfa = alfa
self.a = self.kpr_A = random.randrange(2, self.p-1)
self.kpub_A = pow(self.alfa,self.a)
self.A = self.kpub_A % self.p
print(f"A={self.A}")
self.b = self.kpr_B = random.randrange(2, self.p-1)
self.kpub_B = pow(self.alfa,self.b)
self.B = self.kpub_B % self.p
print(f"B={self.B}")
# Alice B^a mode P
self.Kab1 = pow(self.B, self.a , self.p)
print(self.Kab1)
# Alice A^b mode P
self.Kab2 = pow(self.A, self.b , self.p)
print(self.Kab2)
p = 29
alfa = random.randrange(2, p-1) # 2, p-2
dh = DH(p, alfa)
And the output for Alice and Bob keys:
A=24
B=3
25
25