# Implementing Diffie–Hellman Key Exchange Algorithm in Java

```package diffie;

import java.io.*;
import java.math.BigInteger;
class Diffie
{
public static void main(String[]args)throws IOException
{
System.out.println("Enter prime number:");
System.out.print("Enter primitive root of "+p+":");
System.out.println("Enter value for x less than "+p+":");
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffie hellman secret key Encryption has Taken");
}
}

/* OUTPUT

Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Alice's side:9
Key calculated at Bob's side:9
deffie hellman secret key Encryption has Taken

*/
```

## One thought on “Implementing Diffie–Hellman Key Exchange Algorithm in Java”

1. Tefera says:

how can i generate random values
for the value of p,q and private keys for both client and server?

This site uses Akismet to reduce spam. Learn how your comment data is processed.