我正在尝试使用 Java 创建一个 p2p 协议实现。我编写了 Diffie-Hellman 算法,但后来我面临 MITM 攻击。所以,问题是:如何保护密钥交换?我如何获得...
我正在尝试使用 Java 创建一个 p2p 协议实现。我编写了 Diffie-Hellman 算法,但后来遇到了 MITM 攻击。所以,问题是: 如何保护密钥交换?
public void generateKeys(){
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
keyPairGenerator.initialize(2048);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendPublickKey(){
Message message = new Message(null, null, Base64.getEncoder().encodeToString(publicKey.getEncoded()));
String json = JsonUtils.serializeData(new Data(Data.DataType.PUBLIC_KEY, message, null));
out.println(json);
}
public void receivePublicKey(String encodedPublicKey){
try {
byte[] decodedKey = Base64.getDecoder().decode(encodedPublicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
KeyFactory keyFactory = KeyFactory.getInstance("DH");
receivedPublicKey = keyFactory.generatePublic(keySpec);
generateSharedSecret();
} catch (Exception e) {
e.printStackTrace();
}
}
private void generateSharedSecret() {
try {
KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(receivedPublicKey, true);
byte[] sharedSecret = keyAgreement.generateSecret();
secretKey = new SecretKeySpec(sharedSecret, 0, 32, "AES");
System.out.println("Current session key: " + Base64.getEncoder().encodeToString(secretKey.getEncoded()));
_HCP = new HaritaCP();
validateSecretKey();
Logger.logMessage("Shared secret key generated successfully.", Logger.LogType.info);
} catch (Exception e) {
e.printStackTrace();
}
}