# Implementation of Diffie-Hellman Algorithm in Java

In this tutorial, we are going to learn about the Diffie-Hellman Algorithm in Java.

First of all, we will learn what is Diffie-Hellman Algorithm key exchange algorithm.

## The Diffie-Hellman Algorithm

Diffie-Hellman key exchange Algorithm was discovered by **Whitfield Diffie **and** Martin Hellman.**

First, take **a** as primitive root of a prime number that is p,

If **a** is one of the primitive roots of prime number p, then the numbers,** a mod p, a2 mod p, …….., ap-1 mod p **are distinct and also consist of the integers that are from 1 through p1 in some permutation.

Here, we will implement it using a Java program.

**#Java program.**

## implement Diffie-Hellman Algorithm in Java

Now we will implement the Algorithm in Java. So below is our code to do this task:

import java.util.*; class DiffieHellman { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter the value of modulo(p)"); int p=sc.nextInt(); System.out.println("Enter the root of "+p); int g=sc.nextInt(); System.out.println("select 1st secret no of Alice"); int a=sc.nextInt(); System.out.println("select 2nd secret no of Bob"); int b=sc.nextInt(); int A = (int)Math.pow(g,a)%p; int B = (int)Math.pow(g,b)%p; int S_A = (int)Math.pow(B,a)%p; int S_B =(int)Math.pow(A,b)%p; if(S_A==S_B) { System.out.println("They shared a secret key is = "+S_A); } else { System.out.println("Alice and Bob cannot exchange information with each other"); } } }

enter the value of modulo(p) 23 enter the root of 7 9 select 1st secret no of Alice 4 select 2nd secret no of Bob 3 They shared a secret key is =9.

Finally, we will see some Applications of the Diffie-Hellman key exchange algorithm.

- It is used in Secure Sockets Layer(SSL).
- also, used in secure shell and internet protocol security.

Also, read: Check if a number is special or not in Java

## Leave a Reply