Diffie Hellman key agreement generates different k

2019-04-15 06:12发布

I am experiencing a problem with Diffie Hellman implementation. I am using this code http://www.java2s.com/Tutorial/Java/0490__Security/DiffieHellmanKeyAgreement.htm

It is actually an example from one book I am reading. But I can't understand why generateSecret() creates a different key for every KeyAgreement. I have noticed the function creates different keys even if I call it with the same KeyAgreement twice! If someone has something to suggest I will be really glad!

Thanks for your time!

1条回答
放荡不羁爱自由
2楼-- · 2019-04-15 06:26

I think the part of the example

private static BigInteger g512 = new BigInteger("1234567890", 16);
private static BigInteger p512 = new BigInteger("1234567890", 16);

is completely bogus. p needs to be prime and gneeds to be a generator. When I try running the example I get an exception. This seems to be a more reasonable example (but I haven't tested it myself yet).

Basically the interesting input to the DH exchange is that (p,g) pair which needs to be generated and must have some unique properties. Clearly, the example above shows just place holder values which will not produce a correctly functioning algorithm (p can not be equal to g and p should be prime, while in the example it is clearly divisible by 10). The example I linked to shows how to use the libraries to generate a correct (p, g) pair.

It is also worth noting that DH parameter generation is usually a separate step from generating the secret key. While DH parameters are somewhat private, they are not as sensitive as your private key and can be generated once and then reused.

(Edit: Example)

AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(512); // number of bits
AlgorithmParameters params = paramGen.generateParameters();
DHParameterSpec dhSpec = params.getParameterSpec(DHParameterSpec.class);

BigInteger p512 = dhSpec.getP();
BigInteger g512 = dhSpec.getG();
int l = dhSpec.getL();
...
查看更多
登录 后发表回答