【发布时间】:2017-08-01 06:45:19
【问题描述】:
public static void main(String[] args) throws Exception {
String iv = "0102030405060708";
String key = "1882051051AgVfZUKJLInUbWvOPsAP6LM6nBwLn14140722186";
byte[] aaa = AES_cbc_decrypt("hv208Otx0FZL32GUuErHDLlZzC3zVEGRt56f8lviQpk=", key, iv);
System.out.println(new String(aaa));
}
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
public static byte[] AES_cbc_decrypt(String content,String key,String iv) throws Exception
{
byte[] contentBytes = Base64.decode(content);
byte[] keyBytes = key.substring(0, 16).getBytes();
byte[] ivBytes = iv.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
byte[] decbbdt = cipher.doFinal(contentBytes);
return decbbdt;
}
使用此代码运行,我得到以下异常:
线程“主”javax.crypto.BadPaddingException 中的异常:给定最终块未正确填充
可以通过php方法解密
openssl_decrypt(base64_decode($encryptData), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
【问题讨论】:
-
为什么要将密钥从 50 字节减少到 16 字节? AFAIK 在 php 中它被表示为密码而不是密钥,这意味着它可以是任意长度,并且使用密钥推导函数来生成真正的密钥。
-
你需要展示你完整的php代码。目前尚不清楚 key 和 IV 是如何实际解码的。
-
永远不要在没有参数的情况下使用
String#getBytes,因为默认字符集可能会在不同系统之间发生变化。
标签: java encryption aes