我通过套接字在字节数组中发送Diffie Helman公钥并将其存储在一个文件中,当我需要密钥时,我使用密钥工厂对其进行转换但是当我要将我的私钥和我的合作伙伴关键协议的公钥,doPhase函数,它给我一个不兼容的参数的例外。
public byte[] createMac(byte[] fileBytes, String nick){
byte[] mac = null;
byte[] digest;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(fileBytes);
digest = md.digest();
KeyFactory keyFactory = KeyFactory.getInstance("DH");
byte[] myPrivateKey = Files.readAllBytes(Paths.get(dirMyKeys+"//dhPrivateKey.txt"));
PrivateKey dhPrivKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(myPrivateKey));
byte[] myPublicKey = Files.readAllBytes(Paths.get(dirKeys+"/"+nick+"DhPublicKey.txt"));
System.out.println(dirKeys+"/"+nick+"DhPublicKey.txt");
PublicKey dhPubKey = keyFactory.generatePublic(new X509EncodedKeySpec(myPublicKey));
SecretKey secretKey = combine(dhPrivKey, dhPubKey);
Cipher cipher = Cipher.getInstance("AES");
System.out.println( "\nStart decryption" );
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
mac = cipher.doFinal(digest);
System.out.println( "Finish decryption: " );
return mac;
} catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
return mac;
}
private static SecretKey combine(PrivateKey private1, PublicKey public1) throws NoSuchAlgorithmException, InvalidKeyException {
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(private1);
//error on this line
ka.doPhase(public1, true);
SecretKey secretKey = ka.generateSecret("DES");
return secretKey;
}
这是一个例外:
java.security.InvalidKeyException: Incompatible parameters
at com.sun.crypto.provider.DHKeyAgreement.engineDoPhase(DHKeyAgreement.java:199)
at javax.crypto.KeyAgreement.doPhase(KeyAgreement.java:567)
at safetalk_client.Client.combine(Client.java:279)
at safetalk_client.Client.createMac(Client.java:260)
at safetalk_client.Client.sendFile(Client.java:234)
...
答案 0 :(得分:0)
我没有api的经验,但听起来像是期待不同的输入类型。 diffie-Hellman有一种特定类型的私钥和公钥类,也许它需要那些而不是更通用的声音publickey和privatekey类:
https://docs.oracle.com/javase/7/docs/api/javax/crypto/interfaces/DHPublicKey.html
https://docs.oracle.com/javase/7/docs/api/javax/crypto/interfaces/DHPrivateKey.html
让我知道它是否有效。