当前位置: 首页 > 知识库问答 >
问题:

使用bouncyCastle解密AES-256-cbc

颛孙沈义
2023-03-14

bouncyCastle新手,欢迎提供帮助。我正在尝试使用bounncycastle java API在我的系统上解密一个由第三方加密的文件。它似乎可以很好地解密文件,除了解密文件开头的一团垃圾数据。代码如下

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();
}

解密的数据块看起来很好,除了开头的“?”???

用于解密文件的openssl命令在下面的命令中运行良好。事实上,我在解密时使用的是openssl打印的密钥和iv。

加密文件中的openssl aes-256-cbc-d-salt。txt-pass:password-a-p

共有1个答案

傅越
2023-03-14

解决方案很简单:跳过密文blob的前16个字节。加密的blob从一个魔术开始(您可以尝试读取前8个字节的ASCII文本),然后是8个字节的随机salt,与密码一起用于派生密钥和IV(使用名为EVP\u BytesToKey的OpenSSL专有密码散列机制)。

由于上一个块用作CBC中下一个块的向量,因此16字节的后续块也会受到影响,在开始时为您提供32个随机字节。相反,字节16到31应该与IV进行异或运算。

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

 类似资料:
  • 我在这个网站上用AES-256加密一个虚拟字符串: https://www.devglan.com/online-tools/aes-encryption-decryption 具有以下参数: null 当我尝试用OpenSSL从命令行解密它时: 我得到这个错误:

  • 一定有人知道,在网上没有任何一个工作的例子...

  • 问题内容: 我正在尝试使用PyCrypto构建两个接受两个参数的函数:消息和密钥,然后对消息进行加密/解密。 我在网络上找到了几个链接可以帮助我,但是每个链接都有缺陷: 在codekoala上的此代码使用了os.urandom,PyCrypto不建议这样做。 此外,我不能保证给函数的键具有预期的确切长度。我该怎么做才能做到这一点? 另外,有几种模式,推荐哪种?我不知道该怎么用:/ 最后,IV到底是

  • 我试图使用PyCrypto构建两个函数,它们接受两个参数:消息和密钥,然后加密/解密消息。 我在网上找到了几个帮助我的链接,但每一个都有缺陷: 编辑:删除了代码部分,因为它不安全。

  • 我是密码学的新手。我的要求是对使用openssl加密/解密的文本进行解密/加密。我们在Openssl中使用的算法是aes-256-cbc。因此,我尝试在我的应用程序中实现相同的功能。到目前为止,在谷歌搜索了很多次之后,我所能做的就是。。 我的openssl命令是 我的密钥长度是32位IV是16位 Thnx...