Open In App

Implementation of Diffie-Hellman Algorithm

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 = 

x = G^a mod P

Key generated = 

y = G^b mod P

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

Generated Secret Key = 

k_a = y^a mod P

Generated Secret Key = 

k_b = x^b mod P

Algebraically, it can be shown that 

k_a = k_b

Users now have a symmetric secret key to encrypt

Example: 

Step 1: Alice and Bob get public numbers P = 23, G = 9

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 =(9^4 mod 23) = (6561 mod 23) = 6
Bob: y = (9^3 mod 23) = (729 mod 23) = 16

Step 4: Alice and Bob exchange public numbers

Step 5: Alice receives public key y =16 and
Bob receives public key x = 6

Step 6: Alice and Bob compute symmetric keys
Alice: ka = y^a mod p = 65536 mod 23 = 9
Bob: kb = x^b mod p = 216 mod 23 = 9

Step 7: 9 is the shared secret.

Implementation:  

C++

/* This program calculates the Key for two persons
using the Diffie-Hellman Key exchange algorithm using C++ */
#include <cmath>
#include <iostream>
 
using namespace std;
 
// Power function to return value of a ^ b mod P
long long int power(long long int a, long long int b,
                    long long int P)
{
    if (b == 1)
        return a;
 
    else
        return (((long long int)pow(a, b)) % P);
}
 
// Driver program
int main()
{
    long long int P, G, x, a, y, b, ka, kb;
 
    // Both the persons will be agreed upon the
    // public keys G and P
    P = 23; // A prime number P is taken
    cout << "The value of P : " << P << endl;
 
    G = 9; // A primitive root for P, G is taken
    cout << "The value of G : " << G << endl;
 
    // Alice will choose the private key a
    a = 4; // a is the chosen private key
    cout << "The private key a for Alice : " << a << endl;
 
    x = power(G, a, P); // gets the generated key
 
    // Bob will choose the private key b
    b = 3; // b is the chosen private key
    cout << "The private key b for Bob : " << b << endl;
 
    y = power(G, b, P); // gets the generated key
 
    // Generating the secret key after the exchange
    // of keys
    ka = power(y, a, P); // Secret key for Alice
    kb = power(x, b, P); // Secret key for Bob
    cout << "Secret key for the Alice is : " << ka << endl;
 
    cout << "Secret key for the Bob is : " << kb << endl;
 
    return 0;
}
// This code is contributed by Pranay Arora

                    

C

/* This program calculates the Key for two persons
using the Diffie-Hellman Key exchange algorithm */
#include <math.h>
#include <stdio.h>
 
// Power function to return value of a ^ b mod P
long long int power(long long int a, long long int b,
                    long long int P)
{
    if (b == 1)
        return a;
 
    else
        return (((long long int)pow(a, b)) % P);
}
 
// Driver program
int main()
{
    long long int P, G, x, a, y, b, ka, kb;
 
    // Both the persons will be agreed upon the
    // public keys G and P
    P = 23; // A prime number P is taken
    printf("The value of P : %lld\n", P);
 
    G = 9; // A primitive root for P, G is taken
    printf("The value of G : %lld\n\n", G);
 
    // Alice will choose the private key a
    a = 4; // a is the chosen private key
    printf("The private key a for Alice : %lld\n", a);
    x = power(G, a, P); // gets the generated key
 
    // Bob will choose the private key b
    b = 3; // b is the chosen private key
    printf("The private key b for Bob : %lld\n\n", b);
    y = power(G, b, P); // gets the generated key
 
    // Generating the secret key after the exchange
    // of keys
    ka = power(y, a, P); // Secret key for Alice
    kb = power(x, b, P); // Secret key for Bob
 
    printf("Secret key for the Alice is : %lld\n", ka);
    printf("Secret Key for the Bob is : %lld\n", kb);
 
    return 0;
}

                    

Java

// This program calculates the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
class GFG {
 
    // Power function to return value of a ^ b mod P
    private static long power(long a, long b, long p)
    {
        if (b == 1)
            return a;
        else
            return (((long)Math.pow(a, b)) % p);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        long P, G, x, a, y, b, ka, kb;
 
        // Both the persons will be agreed upon the
        // public keys G and P
 
        // A prime number P is taken
        P = 23;
        System.out.println("The value of P:" + P);
 
        // A primitive root for P, G is taken
        G = 9;
        System.out.println("The value of G:" + G);
 
        // Alice will choose the private key a
        // a is the chosen private key
        a = 4;
        System.out.println("The private key a for Alice:"
                           + a);
 
        // Gets the generated key
        x = power(G, a, P);
 
        // Bob will choose the private key b
        // b is the chosen private key
        b = 3;
        System.out.println("The private key b for Bob:"
                           + b);
 
        // Gets the generated key
        y = power(G, b, P);
 
        // Generating the secret key after the exchange
        // of keys
        ka = power(y, a, P); // Secret key for Alice
        kb = power(x, b, P); // Secret key for Bob
 
        System.out.println("Secret key for the Alice is:"
                           + ka);
        System.out.println("Secret key for the Bob is:"
                           + kb);
    }
}
 
// This code is contributed by raghav14

                    

Python3

# Diffie-Hellman Code
 
 
def prime_checker(p):
    # Checks If the number entered is a Prime Number or not
    if p < 1:
        return -1
    elif p > 1:
        if p == 2:
            return 1
        for i in range(2, p):
            if p % i == 0:
                return -1
            return 1
 
 
def primitive_check(g, p, L):
    # Checks If The Entered Number Is A Primitive Root Or Not
    for i in range(1, p):
        L.append(pow(g, i) % p)
    for i in range(1, p):
        if L.count(i) > 1:
            L.clear()
            return -1
        return 1
 
 
l = []
while 1:
    P = int(input("Enter P : "))
    if prime_checker(P) == -1:
        print("Number Is Not Prime, Please Enter Again!")
        continue
    break
 
while 1:
    G = int(input(f"Enter The Primitive Root Of {P} : "))
    if primitive_check(G, P, l) == -1:
        print(f"Number Is Not A Primitive Root Of {P}, Please Try Again!")
        continue
    break
 
# Private Keys
x1, x2 = int(input("Enter The Private Key Of User 1 : ")), int(
    input("Enter The Private Key Of User 2 : "))
while 1:
    if x1 >= P or x2 >= P:
        print(f"Private Key Of Both The Users Should Be Less Than {P}!")
        continue
    break
 
# Calculate Public Keys
y1, y2 = pow(G, x1) % P, pow(G, x2) % P
 
# Generate Secret Keys
k1, k2 = pow(y2, x1) % P, pow(y1, x2) % P
 
print(f"\nSecret Key For User 1 Is {k1}\nSecret Key For User 2 Is {k2}\n")
 
if k1 == k2:
    print("Keys Have Been Exchanged Successfully")
else:
    print("Keys Have Not Been Exchanged Successfully")

                    

C#

// C# implementation to calculate the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
using System;
class GFG {
 
    // Power function to return value of a ^ b mod P
    private static long power(long a, long b, long P)
    {
        if (b == 1)
            return a;
 
        else
            return (((long)Math.Pow(a, b)) % P);
    }
    public static void Main()
    {
        long P, G, x, a, y, b, ka, kb;
        // Both the persons will be agreed upon the
        // public keys G and P
 
        P = 23; // A prime number P is taken
        Console.WriteLine("The value of P:" + P);
 
        G = 9; // A primitive root for P, G is taken
        Console.WriteLine("The value of G:" + G);
 
        // Alice will choose the private key a
        a = 4; // a is the chosen private key
        Console.WriteLine("\nThe private key a for Alice:"
                          + a);
        x = power(G, a, P); // gets the generated key
 
        // Bob will choose the private key b
        b = 3; // b is the chosen private key
        Console.WriteLine("The private key b for Bob:" + b);
        y = power(G, b, P); // gets the generated key
 
        // Generating the secret key after the exchange
        // of keys
        ka = power(y, a, P); // Secret key for Alice
        kb = power(x, b, P); // Secret key for Bob
 
        Console.WriteLine("\nSecret key for the Alice is:"
                          + ka);
        Console.WriteLine("Secret key for the Alice is:"
                          + kb);
    }
}
 
// This code is contributed by Pranay Arora

                    

Javascript

<script>
 
// This program calculates the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
 
// Power function to return value of a ^ b mod P
function power(a, b, p)
{
    if (b == 1)
        return a;
    else
        return((Math.pow(a, b)) % p);
}
 
// Driver code
var P, G, x, a, y, b, ka, kb;
 
// Both the persons will be agreed upon the
// public keys G and P
 
// A prime number P is taken
P = 23;
document.write("The value of P:" + P + "<br>");
 
// A primitive root for P, G is taken
G = 9;
document.write("The value of G:" + G + "<br>");
 
// Alice will choose the private key a
// a is the chosen private key
a = 4;
document.write("The private key a for Alice:" +
               a + "<br>");
 
// Gets the generated key
x = power(G, a, P);
 
// Bob will choose the private key b
// b is the chosen private key   
b = 3;
document.write("The private key b for Bob:" +
               b + "<br>");
 
// Gets the generated key
y = power(G, b, P);
 
// Generating the secret key after the exchange
// of keys
ka = power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob
 
document.write("Secret key for the Alice is:" +
               ka + "<br>");
document.write("Secret key for the Bob is:" +
               kb + "<br>");
 
// This code is contributed by Ankita saini
 
</script>

                    

Output:

The value of P : 23
The value of G : 9

The private key a for Alice : 4
The private key b for Bob : 3

Secret key for the Alice is : 9
Secret Key for the Bob is : 9

 



Previous Article
Next Article

Similar Reads

Java Implementation of Diffie-Hellman Algorithm between Client and Server
Program to implement Diffie-Hellman Algorithm in Client-Server Fashion. Prerequisite: Server Socket Programming, 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. In the below program, the client will share the valu
4 min read
Applications and Limitations of Diffie-Hellman algorithm
Diffie-Hellman-Algorithm is primarily a protocol that is used for key exchange. Using this interactive protocol two parties will derive a common secret key by communicating each other. The security of Diffie-Hellman algorithm is mainly based on the difficulty of computing the discrete logarithms. Applications of Diffie Hellman AlgorithmMany protoco
2 min read
Difference Between Diffie-Hellman and RSA
Cyber Security is the branch of computers dealing with networks and technology to protect the computer system from unauthorized third-party users which aim at accessing and stealing user information and contribute to causing damage to the system. Cyber security aims at adopting best practices to save computers/ laptops/ mobiles from any kind of cyb
4 min read
Diffie-Hellman Key Exchange and Perfect Forward Secrecy
In the era of modernization where every information has to pass through insecure public networks, where information to always vulnerable to potential active and passive attacks, information security is of paramount importance. Encrypting the information helps a lot of problems as it addresses the issue of confidentiality, where the information is e
8 min read
Which Diffie Hellman Group is Most Secure?
Answer: The most secure Diffie-Hellman group is currently considered to be Group 24 (2048-bit ECP) or higher, offering stronger encryption and resistance to attacks.The security of a Diffie-Hellman (DH) group depends on the size and type of the underlying prime numbers or elliptic curves used. Group 24 (2048-bit ECP)This group uses elliptic curve c
1 min read
Implementation of a Back-off Algorithm for CSMA/CD
Prerequisite - Back-off Algorithm for CSMA/CD Ethernet network may be used to provide shared access by a group of attached nodes to the physical medium which connects the nodes. These nodes are said to form a Collision Domain. When there is data waiting to be sent, each transmitting NIC also monitors its own transmission. If it observes a collision
5 min read
Implementation of RC4 algorithm
RC4 is a symmetric stream cipher and variable key length algorithm. This symmetric key algorithm is used identically for encryption and decryption such that the data stream is simply XORed with the generated key sequence. The algorithm is serial as it requires successive exchanges of state entries based on the key sequence. The algorithm works in t
17 min read
TCP Server-Client implementation in C
Prerequisites - Socket Programming in C/C++, TCP and UDP server using select, UDP Server-Client implementation in C If we are creating a connection between client and server using TCP then it has a few functionalities like, TCP is suited for applications that require high reliability, and transmission time is relatively less critical. It is used by
4 min read
UDP Server-Client implementation in C++
There are two primary transport layer protocols to communicate between hosts: TCP and UDP. Creating TCP Server/Client was discussed in a previous post. Prerequisite: Creating TCP Server/Client Theory: In UDP, the client does not form a connection with the server like in TCP and instead sends a datagram. Similarly, the server need not accept a conne
4 min read
Hamming code Implementation in Java
Pre-requisite: Hamming code Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is a technique developed by R.W. Hamming for error correction. Examples: Input: message bit = 0101 r1 r2 m1 r4 m2 m3 m4 0 1 0 1 Output: Gene
3 min read
Article Tags :