I've learned to write code implementing the Diffie-Hellman key exchange algorithm below, but I feel that my code isn't at its most efficient. Can anyone correct my code please...?
import java.math.BigInteger;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;;
public class DH_key {
static class DHGenParameterSpec implements AlgorithmParameterSpec{
static BigInteger p;
static BigInteger g;
static int a,b;
static BigInteger A,B;
static BigInteger getPrimeP_G() {
Random rand1= new Random(System.currentTimeMillis());
Random rand2= new Random(System.currentTimeMillis()*10);
p= BigInteger.probablePrime(32, rand1);
g= BigInteger.probablePrime(32, rand2);
System.out.println(""+p+","+g);
return null;
}
static int getExponent() {
SecureRandom ranGen1 = new SecureRandom();
a= ranGen1.nextInt(1000);
b= ranGen1.nextInt(1000);
System.out.println(a+"__"+b);
return 0 ;
}
public static Object pow (){
//g.pow(a);
A = g.pow(getExponent()).mod(getPrimeP_G());
B = g.pow(b).mod(p);
return null;
}
public static void main(String[]args){
//System.out.println(DHGenParameterSpec.getPrimeP_G());
DHGenParameterSpec.getPrimeP_G();
DHGenParameterSpec.getExponent();
A = g.pow(a).mod(p);
B = g.pow(b).mod(p);
BigInteger Sa,Sb;
Sa=B.pow(a).mod(p);
Sb=A.pow(b).mod(p);
System.out.println(""+A+"__"+B);
System.out.println(""+Sa+"__"+Sb);
}
}
}
Was the code above appropriate with java rules??
You have written modular exponentiation as:
A = g.pow(getExponent()).mod(getPrimeP_G());
B = g.pow(b).mod(p);
This is inefficient because the intermediate result from the exponentiation can be a large number. You should use the modPow
method instead, which does the two operations with an efficient algorithm:
A = g.modPow(getExponent(), getPrimeP_G());
B = g.modPow(b, p);