c++ - 加载大图像文件在 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.h
from function CallNewHandler()
。
我做错了什么?为什么,.txt 文件加密被同一个程序成功,而 .jpg 却失败了?
解决方案
推荐阅读
- c# - 如何取消数据绑定更改?
- c# - XAML 中的 WPF 绑定到网格列定义中的 C#
- json - 如何使用 groovy 从 JSON 中排除特定字段
- reactive-programming - RxSwift 如何让两个 Observable 绑定在一起完成?
- apache-spark - spark sql中如何设置hive参数和多条语句
- ios - 将 CIImage 的实例转换为 CGImage 的实例,然后才转换为 UIImage 的原因
- node.js - 如何避免在 Puppeteer 和 Phantomjs 上被检测为机器人?
- xcode - nsdata 的文件路径
- docker - Kubernetes 上的 Kafka Chart:简单的测试字符串生产 + 消费
- java - 创建具有不同名称的相同对象而无需循环