我在javaScript中尝试了AES加密,并尝试使用相同的算法和secretKey在java中解密,请有人建议
javaScript 加密
const cipher = crypto.createCipher('aes192','67f969129e2f78f2ee286d16efec0dad');
var encrypted = cipher.update('Hello JavaTpoint', 'utf8', 'base64');
encrypted += cipher.final('base64');
console.log(encrypted); // VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=
加密的base64 key :VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=
java解密
public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException, Exception {
byte[] array = Base64.getDecoder().decode("VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=");
byte[] dec = decrypt(array, "67f969129e2f78f2ee286d16efec0dad");
System.out.println("content is :: dec " + new String(dec));
}
public static byte[] decrypt(byte[] input, String key) {
byte[] decrypted = null;
try {
System.out.println(new String(decodeHexString(key)));
SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
decrypted = cipher.doFinal(input);
} catch (Exception e) {
e.printStackTrace();
}
return decrypted;
}
在java中出现错误:
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:991)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at com.sd.lambda.Decryption.decrypt(Decryption.java:84)
at com.sd.lambda.Decryption.main(Decryption.java:47)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(String.java:566)
at com.sd.lambda.Decryption.main(Decryption.java:50)
它应该被解密并在java控制台中打印“Hello JavaTpoint”,如下所示:
content is :: dec Hello JavaTpoint
最佳答案
当您在 decrypt
方法中调用 cipher.init()
时,IV 是必需的第三个参数。根据原始字符串的加密方式将决定您如何获取该值。
以下是您在设置解密密码时要使用的 init()
方法的链接:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/crypto/Cipher.html#init(int,java.security.Key,java.security.SecureRandom)
关于java - 如何在java中进行AES解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56060804/