I am trying to implement the Diffie Hellman key exchange protocol. For the moment I am stuck at the public parameters generation.
Every time I run the program, p and g parameters are the same (although the method documentation says "This will generate a new key pair every time it is called.").
Could please someone explain to me what am I missing here?
KeyPairGenerator kpg;
try
{
kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512, new SecureRandom());
KeyPair dkp = kpg.generateKeyPair();
DHParameterSpec params =
((javax.crypto.interfaces.DHPublicKey) dkp.getPublic()).getParams();
BigInteger p = params.getP();
BigInteger a = params.getG();
System.out.println(p);
} catch (Exception e)
{
e.printStackTrace();
}
You aren't explicitly initializing the p
and g
values for the Diffie-Hellman exchange, and so they're being initialized to default values. Note that these values are public and have to be shared between the two sides in order for the exchange to work correctly. I ran into a dead end after the third SPI in the Sun JCE, but since you're not setting the parameters yourself, the code is retrieving the same default p
and g
that are used for DSA and applying them to DH.
In case the client does not explicitly initialize the AlgorithmParameterGenerator (via a call to an init method), each provider must supply (and document) a default initialization. For example, the Sun provider uses a default modulus prime size of 1024 bits for the generation of DSA parameters.
The documentation for the Sun implementation lists the following values for 512-bit keys:
p = fca682ce 8e12caba 26efccf7 110e526d b078b05e decbcd1e b4a208f3
ae1617ae 01f35b91 a47e6df6 3413c5e1 2ed0899b cd132acd 50d99151
bdc43ee7 37592e17
g = 678471b2 7a9cf44e e91a49c5 147db1a9 aaf244f0 5a434d64 86931d2d
14271b9e 35030b71 fd73da17 9069b32e 2935630e 1c206235 4d0da20a
6c416e50 be794ca4