【发布时间】:2018-05-19 07:21:15
【问题描述】:
大家好,我在 PHP 中使用 openssl_encrypt 使用算法“aes-256-cbc”加密了字符串
密钥:C4E30455853D4949A8E91B2C366BE9DE
矢量:5686044872102713
加密字符串:ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=
这是我用于解密的 Java 函数:
public static String Decrypt_AES_FromBase64(String AEncryptedText, String AKey32Bytes, String AVectorNum16Bytes) {
try {
byte[] vEncryptedBytes = Base64.getDecoder().decode(AEncryptedText);
Key SecretKey = new SecretKeySpec(AKey32Bytes.getBytes(), "AES");
IvParameterSpec vSpec = new IvParameterSpec(AVectorNum16Bytes.getBytes());
Cipher vCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
vCipher.init(Cipher.DECRYPT_MODE, SecretKey, vSpec);
return new String(vCipher.doFinal(vEncryptedBytes));
} catch (Exception e) {
Common.mContext.getLogger().log(e.toString());
return "";
}
}
当我尝试解密时出现错误:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
谁能告诉我怎么回事?
【问题讨论】:
-
不是突出显示的问题,但 AKey32Bytes.getBytes() 将字符转换为其字符代码,但您可能希望将十六进制数字转换为二进制:In Java, how do I convert a hex string to a byte? 关于如何处理存在一些歧义5686044872102713.
-
我已更改为 IvParameterSpec vSpec = new IvParameterSpec(DatatypeConverter.parseHexBinary(AVectorNum16Bytes));现在我有新错误:“IV 长度错误:必须为 16 字节长”
-
加密的字符串是双Base64编码的,没有理由。
-
可能 IV 不是十六进制(没有 a-f 字符)并且 AES IV 必须是 16 字节。 IV 应该是每次加密的随机字节,只需在加密数据前加上 IV 以用于解密,它不需要保密。
标签: java encryption aes