【发布时间】:2015-08-22 05:02:05
【问题描述】:
bouncyCastle 新手,感谢您的帮助。我正在尝试使用 bouncycastle java API 在我的系统上解密由第三方加密的文件。除了解密文件开头的垃圾数据blob之外,它似乎可以很好地解密文件。下面的代码
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(DatatypeConverter.parseHexBinary(keyInfo.getKey())),
DatatypeConverter.parseHexBinary(keyInfo.getInitializationVector()));
aes.init(false, ivAndKey);
byte[] decryptedBytes = cipherData(aes, Base64.decodeBase64(inputStreamToByteArray(new FileInputStream(encryptedFile))));
return new ByteArrayInputStream(decryptedBytes);
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception {
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
private byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int numberRead;
byte[] data = new byte[16384];
while ((numberRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, numberRead);
}
buffer.flush();
return buffer.toByteArray();
}
解密的数据块看起来很好,除了开头 “???&??ovKw?????C??:?8?06??85042||”
下面的用于解密文件的 openssl 命令可以正常工作。实际上我在解密时使用的是openssl打印出来的密钥和iv。
openssl aes-256-cbc -d -salt -in encryptedfile.txt -pass pass:password -a -p
【问题讨论】:
-
打印随机字节时,请使用BouncyCastle
Hex.encodeToString(byte[])方法。
标签: java encryption cryptography bouncycastle