-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdiffie-hellman.java
54 lines (43 loc) · 1.24 KB
/
diffie-hellman.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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 primitve 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);
}
}