How to do Diffie Hellman Key Generation and retrieve raw key bytes in Java

时间秒杀一切 提交于 2019-12-07 06:36:49

问题


I am writing a test harness in java for an existing program. As part of this i need to generate a Diffie Hellman key pair and pass the public key to the other program in its raw (i.e unencoded bytes) form.

I can successfully the key pair using the following code:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair dkp = kpg.generateKeyPair();

However, i cannot seem to retrieve the raw byte value of the keys :-( Calling dkp.getPublic().getEncoded() returns a byte array but its of the Key in an x509 encoded format.

Three possible ways forward occur to me:

  1. Find some method of getting the key data out of the above in its raw form.
  2. Decode the x509 encoding of the key into its raw form
  3. Generate the keys in a different manner that allows access to the raw key

But im not how to go about doing any of them (and which will turn out to be best)?

Any help or advice would be greatly appreciated!


回答1:


You can get the X and Y (where Y = G^X mod P) values like this:

 BigInteger x = ((javax.crypto.interfaces.DHPrivateKey) dkp.getPrivate()).getX();
 BigInteger y = ((javax.crypto.interfaces.DHPublicKey) dkp.getPublic()).getY();

You can get the G and P values from either the public or private key like this:

DHParameterSpec params = 
    ((javax.crypto.interfaces.DHPublicKey) dkp.getPublic()).getParams();
BigInteger p = params.getP();
BigInteger g = params.getG();

From there you can get them all as raw byte arrays:

 byte[] xBytes = x.toByteArray();
 byte[] yBytes = y.toByteArray();
 byte[] pBytes = p.toByteArray();
 byte[] gBytes = g.toByteArray();

The combination of Y, P, and G make the public key. X should be kept secret.



来源:https://stackoverflow.com/questions/19323178/how-to-do-diffie-hellman-key-generation-and-retrieve-raw-key-bytes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!