我不明白为什么我总是收到以下代码的异常:
public class AES {
/*Some private vars (not shown)*/
public AES(String secretKey, String initVector, String plainText, String cipherText, String addAuthData, String authTag) throws NoSuchAlgorithmException, NoSuchPaddingException {
//Initialize test values
this.cipher = Cipher.getInstance("AES/GCM/NoPadding");
this.K = new SecretKeySpec(Dump.hexString2byteArray(secretKey), "AES");
this.IV = Dump.hexString2byteArray(initVector);
this.C = Dump.hexString2byteArray(cipherText);
this.A = Dump.hexString2byteArray(addAuthData);
this.T = Dump.hexString2byteArray(authTag);
this.t = this.T.length*8;
this.gcmIv = new GCMParameterSpec(t, IV);
}
public String testDecryption() throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
cipher.init(Cipher.DECRYPT_MODE, K, gcmIv);
cipher.updateAAD(A);
cipher.init(Cipher.DECRYPT_MODE, K, gcmIv);
cipher.doFinal(C);
return "Return later some string";
}
这是我如何运行代码的示例:
AES testCase4 = new AES(
"feffe9928665731c6d6a8f9467308308",
"cafebabefacedbaddecaf888",
"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39",
"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091",
"feedfacedeadbeeffeedfacedeadbeefabaddad2",
"5bc94fbc3221a5db94fae95ae7121a47"
);
String TC4_p = testCase4.testDecryption();
有人能解释一下吗? 该错误来自 cipher.doFinal(C);
行最佳答案
您的源代码中有 2 个问题。在 native Java 中,身份验证标记(“authTag”)与密文(“C”)连接在一起,因此您对该类的初始化应该是
this.C = Dump.hexString2byteArray(cipherText + authTag);
其次,在 test.Decryption 中,您初始化密码两次,省略第二行
cipher.init(Cipher.DECRYPT_MODE, K, gcmIv);
这样解密就能正确进行
"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"
关于Java AES GCM javax.crypto.AEADBadTagException : Tag mismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003904/