- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathDiffieHellman.java
36 lines (30 loc) · 1.33 KB
/
DiffieHellman.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
packagecom.thealgorithms.ciphers;
importjava.math.BigInteger;
publicfinalclassDiffieHellman {
privatefinalBigIntegerbase;
privatefinalBigIntegersecret;
privatefinalBigIntegerprime;
// Constructor to initialize base, secret, and prime
publicDiffieHellman(BigIntegerbase, BigIntegersecret, BigIntegerprime) {
// Check for non-null and positive values
if (base == null || secret == null || prime == null || base.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) {
thrownewIllegalArgumentException("Base, secret, and prime must be non-null and positive values.");
}
this.base = base;
this.secret = secret;
this.prime = prime;
}
// Method to calculate public value (g^x mod p)
publicBigIntegercalculatePublicValue() {
// Returns g^x mod p
returnbase.modPow(secret, prime);
}
// Method to calculate the shared secret key (otherPublic^secret mod p)
publicBigIntegercalculateSharedSecret(BigIntegerotherPublicValue) {
if (otherPublicValue == null || otherPublicValue.signum() <= 0) {
thrownewIllegalArgumentException("Other public value must be non-null and positive.");
}
// Returns b^x mod p or a^y mod p
returnotherPublicValue.modPow(secret, prime);
}
}