首页 > 解决方案 > 加载大图像文件在 CryptoPP::FileSource 中引发异常 std::bad_alloc

问题描述

在一个 c++ 项目中,我使用 CryptoPP 对图像文件执行 AES/CBC/PKCS5Padding 加密。下面是我正在使用的代码(来自Storing the IV with the ciphertext Crypto++ CBC AES encryption

#include <iostream>
#include <osrng.h>
#include <files.h>
#include <modes.h>

using namespace std;
using namespace CryptoPP;

int main()
{
    cout << "Hello World!\n";

    AutoSeededRandomPool prng;
    SecByteBlock iv(AES::BLOCKSIZE);
    string _key = "0123456789abcdef";
    SecByteBlock key((const byte*)_key.data(), _key.size());

    RandomNumberSource rs2(prng, AES::BLOCKSIZE, new ArraySink(iv, iv.size()));

    CBC_Mode<AES>::Encryption encryptor;
    encryptor.SetKeyWithIV(key, key.size(), iv, iv.size());


    // Plaintext message
    ByteQueue queue;
    FileSource source("E:\\ori_pics\\20161224_143119.jpg", true, new Redirector(queue));

    SecByteBlock block(queue.MaxRetrievable());
    ArraySink sink(block, block.size());
    queue.TransferTo(sink);

    // Output file
    FileSink file("D:\\enc_pics\\20161224_143119.jpg");

    // Source wrappers
    ArraySource as(iv, iv.size(), true, new Redirector(file));
    ArraySource ss(block, block.size(), true, new StreamTransformationFilter(encryptor, new Redirector(file), BlockPaddingSchemeDef::PKCS_PADDING));

}

在这个程序中,我使用随机 IV 和固定密钥。我在输出文件的开头写 IV,然后用PKCS_PADDING.

当我使用 .txt 文件作为输入时,上面的程序运行良好,它正在生成加密的 txt 文件。但是,当我提供大小为 55,35,433 字节(大约 5MB)的 .jpg 文件时std::bad_alloc,代码行会引发异常: FileSource source("E:\\ori_pics\\20161224_143119.jpg", true, new Redirector(queue));from file misc.hfrom function CallNewHandler()

我做错了什么?为什么,.txt 文件加密被同一个程序成功,而 .jpg 却失败了?

标签: c++cryptographycrypto++

解决方案


推荐阅读