我使用特定的Java工具和BooCyCaseAdvor为特定的AES算法实现了具有特定任务特定参数的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
我的目标是使用第三方库重新实现它,理想情况下我将使用已经用作提供者的BouncyCastle。该库不应该对标准Java策略文件进行删除。换句话说,不应该有任何限制。
请在您的答案中建议如何使用BouncyCastle或其他第三方库重新实现它,这些库可以不受上述限制地工作。理想情况下,我会看到代码:—)
非常感谢你的阅读!
经过一段时间的耽搁,我现在很乐意发布一个解决方案。希望有人能从中受益,因为BouncyCastle文档中没有很多示例:—)
private byte[] aesEncryptedInfo(String info)
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和PosiCype API之间有两个不同点:
1。BouncyCastle使用对象组合来创建所需的密码。而Java API使用字符串来标识需要的密码。
2。BC加密代码稍大一些,而Java API代码更紧凑。
解决方案是完全替换原来的Java API实现——证明是我做的一个定制单元测试。