我已经使用标准 Java 工具和针对特定 AES 算法的 BouncyCastle 提供程序使用某些特定于任务的参数实现了 AES 加密。
这是代码:
private byte[] aesEncryptedInfo(String info) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidAlgorithmParameterException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
SecretKey secret = new SecretKeySpec(CUSTOMLONGSECRETKEY.substring(0, 32).getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(VECTOR_SECRET_KEY.getBytes()));
return cipher.doFinal(info.getBytes("UTF-8"));
}
在某些环境中,此代码需要特殊的策略文件。请参阅相关问题:InvalidKeyException Illegal key size
我的目标是使用第三方库重新实现它,理想情况下我会使用已经用作提供者的充气城堡。该库不应限制标准 java 策略文件。换句话说,不应该有任何限制。
请在您的回答中建议如何使用 BouncyCastle 或其他可以不受限制地工作的第三方库重新实现它。理想情况下,我会看到代码:-)
非常感谢您的阅读!
延迟后,我现在很高兴发布解决方案。希望有人可以从中受益,因为 Bouncy Castle 文档中没有很多示例 :-)
private byte[] aesEncryptedInfo(String info)
// Creating AES/CBC/PKCS7Padding cipher with specified Secret Key and Initial Vector
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
cipher.init(true, new ParametersWithIV(new KeyParameter(CUSTOMLONGSECRETKEY.getBytes()), VECTOR_SECRET_KEY.getBytes()));
byte[] inputData = info.getBytes("UTF-8");
int outBlockSize = cipher.getOutputSize(inputData.length);
byte[] outputData = new byte[outBlockSize];
int outLength = cipher.processBytes(inputData, 0, inputData.length, outputData, 0);
outLength += cipher.doFinal(outputData, outLength);
if (outLength != outBlockSize) {
return Arrays.copyOf(outputData, outLength);
}
else {
return outputData;
}
}
顺便说一句,我发现 Java API 和 Bouncy Castle API 之间有两个区别: 1. Bouncy Castle 使用对象组合来创建所需的密码。而 Java API 使用字符串来识别所需的密码。2. BC 加密代码略大,而 Java API 代码更紧凑。
该解决方案完全替代了原始 Java API 实现——证明是我制作的自定义单元测试。