使用bouncycastle解密aes-256-cbc

bouncyCastle新手,任何帮助表示赞赏。 我正在尝试使用bounncycastle 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(); } 

解密数据blob看起来很好,除了开头“???&?? ovKw ????? C ??:?8?06 ?? 85042 | |”

解密文件的openssl命令在下面工作正常。 事实上,我正在使用密钥并在解密时由openssl打印出来。

openssl aes-256-cbc -d -salt -in encryptedfile.txt -pass pass:password -a -p

解决方案很简单:跳过密文blob的前16个字节。 加密的blob以魔术开始(您可以尝试将前8个字节读取为ASCII文本),然后将8个字节的随机盐与密码一起使用以获取密钥和IV(使用OpenSSL专有密码散列机制)叫做EVP_BytesToKey )。

因为前一个块用作CBC中下一个块的向量,所以16个字节的后续块也会受到影响,在开始时会给你32个随机字节。 相反,字节16到31应该与IV进行异或。

这是使用我的旧昵称发布的BytesToKey的Java实现 。