# Diffie-Hellman algorithm implementation in Python

In this tutorial, we are going to implement the Diffie-Hellman key exchange Algorithm in Python.

In this tutorial, we are going to implement the Diffie-Hellman key exchange Algorithm in Python.

The Diffie–Hellman key exchange protocol, conceived by Ralph Merkle and named after Whitfield Diffie and Martin Hellman, is a method of securely exchanging cryptographic keys over a public channel.

Algorithm with an example:

Step 1: A and B agrees on prime number (p) = 11 and primitive root (g) = 7

Step 2: A chooses a private key xa = 3 and
B chooses a private key xb = 6 ;such that xa

Step 3: A and B both computed public key for them as follows:
A: ya =(g^xa)modp =(7^3)mod11 =2
B: yb =(g^xa)modp =(7^6)mod11 =4

Step 4: Both A and B exchanges their public key
So now A receives yb = 4 and B receives ya = 2

Step 5: Now A and B both calculates their shared secret key as
A: ka =(yb^xa)modp =(4^3)mod11 =9
B: kb =(ya^xb)modp =(2^6)mod11 =9

So 9 is the shared secret key.

The Diffie-Hellman algorithm's code is written in Python, and the output for the same is :

Enter Prime No. p : 11
Enter Primitive root (g<p) : 7
Enter Private key of A (xa<p) : 3
Enter Private key of B (xb<p) : 6
A’s Public Key Ya = 2
B’s Public Key Yb = 4
Shared secret key k = 9