Wudong Wudong - 4 months ago 10x
Java Question

How to combine a private key and a public key for a shared secret in Java

I'm reading the wikipedia about public-key Public-key cryptography ( http://en.wikipedia.org/wiki/Public-key_cryptography ) and in it it says:

In the Diffie–Hellman key exchange scheme, each party generates a public/private key pair and distributes the public key... After obtaining an authentic copy of each other's public keys, Alice and Bob can compute a shared secret offline. The shared secret can be used, for instance, as the key for a symmetric cipher.

I'm wondering how to achieve this in Java? i.e., given an arbitrary public-key and an arbitary private-key, how to generate a share-secret from it?

To make it more clear:

Alice has a public/private key pair key_pair_alice,

Bob has a public/private key pair key_pair_bob,

Assuming my understanding is right, there should be a method combine_keys() so that:

combine_keys(key_pair_alice.private, key_pair_bob.public) ==
combine_keys(key_pair_alice.public, key_pair_bob.private)

My question is how to implement the combine_keys() method in Java.



After some research, I have come up with the solution using Java's crypto package.

 public static void main(String[] args) {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator

// Generate the parameters
AlgorithmParameters params = paramGen.generateParameters();
DHParameterSpec dhSpec = (DHParameterSpec) params


KeyPair alice_key = keyGen.generateKeyPair();
KeyPair bob_key = keyGen.generateKeyPair();

SecretKey secret_alice = combine(alice_key.getPrivate(),

SecretKey secret_bob = combine(bob_key.getPrivate(),


private static SecretKey combine(PrivateKey private1,
    PublicKey public1)  {
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.doPhase(public1, true);
SecretKey secretKey = ka.generateSecret("DES");
return secretKey;

The sysout in the end shows that alice and bob now shares a same secrete.