Diffie-Hellman Key Exchange
Module 03 / Lesson 03
Handshake Explanation
How Secure Key Exchange Works
Diffie-Hellman is a method for securely generating a shared secret key over an unsecured medium. It relies on the mathematical difficulty of the Discrete Logarithm Problem.
Alice's Side:
- Choose secret a
- Compute $A = g^a \pmod p$
- Send A to Bob
- Final: $K = B^a \pmod p$
Bob's Side:
- Choose secret b
- Compute $B = g^b \pmod p$
- Send B to Alice
- Final: $K = A^b \pmod p$
Numerical Example:
Public: $p=23, g=5$. Alice secret $a=6$, Bob secret $b=15$.
Alice sends $A = 5^6 \pmod{23} = 8$. Bob sends $B = 5^{15} \pmod{23} = 19$.
Shared Secret: $19^6 \pmod{23} = 8^{15} \pmod{23} = \mathbf{2}$.
Python Implementation (Handshake)
def dh_handshake():
# Public parameters
p = 23
g = 5
# 1. Alice selects secret 'a' and computes 'A'
a_secret = 6
A_public = pow(g, a_secret, p)
# 2. Bob selects secret 'b' and computes 'B'
b_secret = 15
B_public = pow(g, b_secret, p)
# 3. Exchange and compute shared secret
alice_key = pow(B_public, a_secret, p)
bob_key = pow(A_public, b_secret, p)
print(f"Alice's computed key: {alice_key}")
print(f"Bob's computed key: {bob_key}")
dh_handshake() # Both will print '2'