@@ -10,6 +10,10 @@ public final class DiffieHellman {
10
10
11
11
// Constructor to initialize base, secret, and prime
12
12
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
+ }
13
17
this .base = base ;
14
18
this .secret = secret ;
15
19
this .prime = prime ;
@@ -23,16 +27,27 @@ public BigInteger calculatePublicValue() {
23
27
24
28
// Method to calculate the shared secret key (otherPublic^secret mod p)
25
29
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
+ }
26
33
// Returns b^x mod p or a^y mod p
27
34
return otherPublicValue .modPow (secret , prime );
28
35
}
29
36
30
37
// Static utility methods for direct calculation (if needed)
31
38
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
+ }
32
43
return base .modPow (secret , prime );
33
44
}
34
45
35
46
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
+ }
36
51
return otherPublicValue .modPow (secret , prime );
37
52
}
38
53
}
0 commit comments