【发布时间】:2019-05-09 13:42:35
【问题描述】:
我在 javaScript 中尝试了 AES 加密,并尝试在 java 中使用相同的算法和 secretKey 解密,请任何人建议
javaScript 加密
const cipher = crypto.createCipher('aes192','67f969129e2f78f2ee286d16efec0dad');
var encrypted = cipher.update('Hello JavaTpoint', 'utf8', 'base64');
encrypted += cipher.final('base64');
console.log(encrypted); // VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=
加密的 base64 密钥: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
【问题讨论】:
标签: java