Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 40e69d2

Browse files
authoredOct 2, 2024··
Update DiffieHellman.java
1 parent f2ccca5 commit 40e69d2

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
 

‎src/main/java/com/thealgorithms/ciphers/DiffieHellman.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ public final class DiffieHellman {
1010

1111
// Constructor to initialize base, secret, and prime
1212
public DiffieHellman(BigInteger base, BigInteger secret, BigInteger prime) {
13+
// Check for non-null and positive values
14+
if (base == null || secret == null || prime == null || base.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) {
15+
throw new IllegalArgumentException("Base, secret, and prime must be non-null and positive values.");
16+
}
1317
this.base = base;
1418
this.secret = secret;
1519
this.prime = prime;
@@ -23,16 +27,27 @@ public BigInteger calculatePublicValue() {
2327

2428
// Method to calculate the shared secret key (otherPublic^secret mod p)
2529
public BigInteger calculateSharedSecret(BigInteger otherPublicValue) {
30+
if (otherPublicValue == null || otherPublicValue.signum() <= 0) {
31+
throw new IllegalArgumentException("Other public value must be non-null and positive.");
32+
}
2633
// Returns b^x mod p or a^y mod p
2734
return otherPublicValue.modPow(secret, prime);
2835
}
2936

3037
// Static utility methods for direct calculation (if needed)
3138
public static BigInteger calculatePublicValue(BigInteger base, BigInteger secret, BigInteger prime) {
39+
// Check for valid inputs
40+
if (base == null || secret == null || prime == null || base.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) {
41+
throw new IllegalArgumentException("Base, secret, and prime must be non-null and positive values.");
42+
}
3243
return base.modPow(secret, prime);
3344
}
3445

3546
public static BigInteger calculateSharedSecret(BigInteger otherPublicValue, BigInteger secret, BigInteger prime) {
47+
// Check for valid inputs
48+
if (otherPublicValue == null || secret == null || prime == null || otherPublicValue.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) {
49+
throw new IllegalArgumentException("Other public value, secret, and prime must be non-null and positive values.");
50+
}
3651
return otherPublicValue.modPow(secret, prime);
3752
}
3853
}

0 commit comments

Comments
 (0)
Please sign in to comment.