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

1

5

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!

Hysteroid answered 11/10, 2013 at 16:40 Comment(0)
S
9

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.

Speaks answered 11/10, 2013 at 16:48 Comment(2)
Just got round to trying this and it works perfectly :-) Thank you very much for your help.Hysteroid
@Speaks Nice...but how to get symmetric key using server Public key.Clothesline

© 2022 - 2024 — McMap. All rights reserved.