使用 bouncycastle 解密 aes-256-cbc

Decrypting aes-256-cbc using bouncycastle

bouncyCastle 的新手,感谢任何帮助。我正在尝试使用 bounncycastle java API 在我的系统上解密由第三方加密的文件。似乎可以很好地解密文件,除了

下面解密的 file.Code 开头的垃圾数据块
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打印出来的key和iv。

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 进行异或运算。

这里 a Java implementation of BytesToKey 使用我的旧昵称发布。