0

I have a small program that starts by exchanging session key for communication and for that it use Diffie-Hellman key agreement. In Java first part is done like this:

KeyPairGenerator keyPairGenerator1 = KeyPairGenerator.getInstance("DH");
keyPairGenerator1.initialize(Skip.sDHParameterSpec);
KeyPair keyPair1 = keyPairGenerator1.generateKeyPair();
byte[] localKey1 = keyPair1.getPublic().getEncoded();
KeyAgreement keyAgreement1 = KeyAgreement.getInstance("DH");
keyAgreement1.init(keyPair1.getPrivate());
// getting remote key 
keyAgreement1.doPhase(theirPublicKey2, true);
byte[] sharedKey1 = keyAgreement1.generateSecret();

then localKey is sent to the remote part, who sends back they part of data for calculation DH shared key. Problem, another program expects to get row data (big integer), and from java program I sent X509 encoded.

So how can I get that BigInteger (local Y value of DH protocol) from PublicKey? Or maybe there's another way to generate necessary DH parameters?

Bruno Rohée
  • 3,436
  • 27
  • 32
Dainius
  • 1,765
  • 1
  • 17
  • 36

1 Answers1

1

Just cast the key to a more specialized type...

DHPublicKey localKey = (DHPublicKey) keyPair1.getPublic();
BigInteger localY = localKey.getY();

Of course, if you haven't agreed on pre-defined parameters you may want to retrieve the parameters from the localKey as well.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Oh, uh, don't forget to verify the parameters and don't forget that DH in itself helps against eavesdropping only... – Maarten Bodewes Oct 30 '12 at 20:52
  • I thought I tried "keyPair.getPublic() instanceof DHPublicKey" but apparently not (or checked something else then). Thanks for answer. – Dainius Oct 31 '12 at 06:59
  • Maybe http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom helps? – Maarten Bodewes Oct 31 '12 at 13:50