如何在Java中为私有密钥和公共密钥组合共享密钥

我正在阅读有关公钥公钥加密(http://en.wikipedia.org/wiki/Public-key_cryptography)的维基百科,其中包含:

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.

我想知道如何在Java中实现这一目标?即,如果给出一个任意的公钥和一个任意的私钥,如何从中产生一个共享秘密?

为了更清楚:

Alice有一个公钥/私钥对key_pair_alice,

Bob有一个公钥/私钥对key_pair_bob,

假设我的理解是正确的,那么应该有一个方法combine_keys(),以便:

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

我的问题是如何在Java中实现combine_keys()方法.

谢谢.

最佳答案
经过一些研究,我使用Java的加密包提出了解决方案.

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

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

keyGen.initialize(dhSpec);

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

SecretKey secret_alice = combine(alice_key.getPrivate(),
    bob_key.getPublic());

SecretKey secret_bob = combine(bob_key.getPrivate(),
    alice_key.getPublic());

System.out.println(Arrays.toString(secret_alice.getEncoded()));
System.out.println(Arrays.toString(secret_bob.getEncoded()));
}

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

最后的sysout表明alice和bob现在共享相同的秘密.

转载注明原文:如何在Java中为私有密钥和公共密钥组合共享密钥 - 代码日志