Diffie-Hellman 在 Java 中的密钥交换
2022-09-04 19:36:07
我正在用Java进行一个个人项目,该项目涉及通过不安全的通道发送敏感数据。我需要知道如何使用其库在java中实现Diffie Hellman密钥交换(DHKE)。我知道所有关于它的加密理论,所以不需要详细介绍,我只需要一个非常基本的实现,所以我可以让2个程序共享一个密钥。我从 java2s.com 那里得到了这个例子,但它并不完整:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
public class Main {
public final static int pValue = 47;
public final static int gValue = 71;
public final static int XaValue = 9;
public final static int XbValue = 14;
public static void main(String[] args) throws Exception {
BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new BigInteger(Integer.toString(XaValue));
BigInteger Xb = new BigInteger(Integer.toString(XbValue));
int bitLength = 512; // 512 bits
SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpec param = new DHParameterSpec(p, g);
kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
}
}
我该如何继续呢?任何人都可以帮我完成剩余的代码吗?