Diffie-Hellman Key Exchange

Last modified: 2023-07-26


Diffie-Hellman key exchange is a mathematical method for exchaning cryptographic key securely.


DH calculates shared secrets with public keys and secret keys. Below is a Python script to calculate shared secrets for A and B. These (ss_A and ss_B) should be the same value with each other.

# Calculate A, B
# p: public key (a prime number)
# g: public key (a primitive root modulo `p`)
# a, b: secret key
A = pow(g, a, p)
B = pow(g, b, p)

# Calculate shared secret
ss_A = pow(A, b, p)
ss_B = pow(B, a, p)

# Shared secrets should be the same value each other
print(ss_A == ss_B) # True
print(pow(pow(g, a, p), b, p) == pow(pow(g, b, p), a, p)) # True