VOOZH about

URL: https://www.geeksforgeeks.org/computer-networks/implementation-diffie-hellman-algorithm/

⇱ Implementation of Diffie-Hellman Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implementation of Diffie-Hellman Algorithm

Last Updated : 3 Feb, 2026

Diffie-Hellman algorithm:

The Diffie-Hellman algorithm is being used to establish a shared secret that can be used for secret communications while exchanging data over a public network using the elliptic curve to generate points and get the secret key using the parameters.  

  • For the sake of simplicity and practical implementation of the algorithm, we will consider only 4 variables, one prime P and G (a primitive root of P) and two private values a and b.
  • P and G are both publicly available numbers. Users (say Alice and Bob) pick private values a and b and they generate a key and exchange it publicly. The opposite person receives the key and that generates a secret key, after which they have the same secret key to encrypt.


Step-by-Step explanation is as follows:  

AliceBob
Public Keys available = P, GPublic Keys available = P, G
Private Key Selected = aPrivate Key Selected = b

Key generated = 

Key generated = 

Exchange of generated keys takes place
Key received = ykey received = x

Generated Secret Key = 

Generated Secret Key = 

Algebraically, it can be shown that 

Users now have a symmetric secret key to encrypt

Example:

Step 1: Alice and Bob get public numbers P = 23, G = 5
Step 2: Alice selected a private key a = 4 and
Bob selected a private key b = 3
Step 3: Alice and Bob compute public values
Alice: x =(5^4 mod 23) = (625 mod 23) = 4
Bob: y = (5^3 mod 23) = (125 mod 23) = 10
Step 4: Alice and Bob exchange public numbers
Step 5: Alice receives public key y =10 and
Bob receives public key x = 4
Step 6: Alice and Bob compute symmetric keys
Alice: ka = y^a mod p = 10000 mod 23 = 18
Bob: kb = x^b mod p = 64 mod 23 = 18
Step 7: 18 is the shared secret.

You can find more detail on what primitive roots of a number are in this article : Primitive root of a prime number n modulo n.

For our example the number 23(prime) has the following primitive roots : [5, 7, 10, 11, 14, 15, 17, 19, 20, 21].

Implementation:

Output:

👁 Screenshot-2026-02-03-171959



Comment
Article Tags:

Explore