I have the line of code below to generate a private key:
int Xa = randomNo.nextInt(10000);
int Ya = (int) Math.pow(G, Xa) % P;
G
and P
are static numbers. Whereas Xa
is randomly generated. Every time I run the program, it gives me the same result for Ya
. Is this correct for Diffie-Hellman? I thought the private key had to be changed every time the algorithm was run.
I think the problem may be that you are overflowing double with your exponentiation, resulting in infinity, resulting in the same value every time (unless you are lucky enough to end up with a very low number returned for your exponent).
Also, be sure to use secure random to get your random value:
Random random = new SecureRandom();
// If you use more than 100 here, then
// with your value of 486 for G you will
// end up with infinity when doing Math.pow(G,Xa).
// Of course, this does not provide enough possible
// values to be cryptographically secure.
int Xa = random.nextInt(100);
int Ya = (int) (Math.pow(G, Xa) % P);
Edit: Code with debugging (the below works for me):
double G = 42;
int P = 26;
Random random = new SecureRandom();
int Xa = random.nextInt(100);
double val = Math.pow(G, Xa);
System.out.println("Xa: " + Xa);
System.out.println("(double) Math.pow: " + val + " (int): " + (int) val);
int Ya = (int) (val % P);
System.out.println("Ya: " + Ya);