【发布时间】:2017-04-03 06:09:18
【问题描述】:
我们最近将基础架构从 Solaris(Oracle/Sun Java) 迁移到 AIX(IBM Java)。
我们的客户将使用我们共享的算法(AES)和密钥上传加密文件,一旦将加密文件放入我们的服务器,批处理例程将使用相同的密钥解密。这在迁移之前运行良好,但在迁移后,AES 解密功能不起作用。
我们之前用过
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
迁移后,我们已将其更改为
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
当批处理执行时,我们得到如下异常
javax.crypto.IllegalBlockSizeException:输入长度(带填充)不是 16 字节的倍数 在 com.ibm.crypto.provider.AESCipher.a(未知来源) 在 com.ibm.crypto.provider.AESCipher.engineDoFinal(未知来源) 在 com.ibm.crypto.provider.AESCipher.engineDoFinal(未知来源) 在 javax.crypto.Cipher.doFinal(Unknown Source)
用于解密的代码
private byte[] decrypt(byte[] data, String corporateId, String algorithm)
throws Exception {
String path = corporateId + ".key";
byte[] key = (byte[]) null;
try {
key = returnbyte(path);
} catch (IOException e) {
e.printStackTrace();
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
this.logger.info("Provider Info " + cipher.getProvider().getInfo());
byte[] keyBytes = new byte[16];
int len = key.length;
if (len > keyBytes.length) {
len = keyBytes.length;
}
System.arraycopy(key, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(2, keySpec, ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte[] results = decoder.decodeBuffer(hexStringFromBytes(data));
byte[] ciphertext = cipher.doFinal(results);
return ciphertext;
}
hexStringFromBytes 方法:
public static String hexStringFromBytes(byte[] ba) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ba.length; i++) {
if ((i > 0) && ((i & 0x1F) == 0)) {
sb.append("\n");
} else if ((i > 0) && ((i & 0x3) == 0)) {
sb.append("");
}
sb.append(hexChars[((0xF0 & ba[i]) >> 4)]);
sb.append(hexChars[(0xF & ba[i])]);
}
return sb.toString();
}
不确定问题的原因,cipher.doFinal(results); 抛出错误。
类加载器还显示正在使用的 IBMJCE 提供程序。被这个问题困扰了3天。非常感谢任何解决问题的方向或指导。提前致谢。
【问题讨论】:
-
输入是否是块大小的精确倍数(AES 为 16 字节)?调试并找出原因,这不是原因。
-
您将
byte[]数据转换为十六进制字符串,然后进行base64 解码?这根本没有意义。 -
请注意,OP 是“技术架构师”。
标签: java encryption aes aix