Pregunta

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!

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top