Diffie-Hellman key exchange

Textbook key exchange

from Crypto.Util.number import getPrime

q = getPrime(1024)
p = q * 2 + 1
g = 2

# Alice
## Private key
a = getPrime(1024)
## Public key
A = pow(g, a, p)
## Send A to Bob

# Bob
## Private key
b = getPrime(1024)
## Public key
B = pow(g, b, p)
## Shared secret
s_bob = pow(A, b, p)
## Send B to Alice

# Alice
## Shared secret
s_alice = pow(B, a, p)

print(s_alice == s_bob)
# True

Now both Alice and Bob each have the same shared secret without revealing private information with each other. Someone snooping on the conversation will not be able to know Alice’s or Bob’s private key or their shared secret without solving the discrete log problem. However, without authentication an active man-in-the-middle can still defeat security of the key exchange.