我编写了一些包装函数来使用 crypto++ 加密/解密文件。我尝试查看维基,但可以找到我的答案。我想知道是否需要显式销毁创建的对象?
我在 wiki 中发现传递给函数的某些对象会为您销毁,但没有我确切使用的示例,所以我只是想确定一下。
CryptoPP::AutoSeededRandomPool prng;
//Key generation
byte key[AES::DEFAULT_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
//IV generation
byte iv[AES::BLOCKSIZE];
prng.GenerateBlock(iv, sizeof(iv));
//print key
encoded.clear();
StringSource(key, sizeof(key), true, new HexEncoder(new StringSink(encoded)));
cout << "key: " << encoded << endl;
cout << "Size of key: " << sizeof(key) << endl;
//print iv
encoded.clear();
StringSource(iv, sizeof(iv), true, new HexEncoder(new StringSink(encoded)));
cout << "iv: " << encoded << endl;
cout << "Size of iv: " << sizeof(iv) << endl;
//See function below
encrypt_file(inFile, outFile, key, iv, err);
inFile.close();
outFile.close();
在这个函数中,字节数组由于某种原因被截断
加密文件
bool encrypt_file(std::ifstream& inFile,
std::ofstream& outFile,
const byte* key, const byte* iv,
std::string& errMsg)
{
std::string encoded;
//print key
encoded.clear();
StringSource(key, sizeof(key), true, new HexEncoder(new StringSink(encoded)));
cout << "key: " << encoded << endl;
cout << "Size of key: " << sizeof(key) << endl;
//print iv
encoded.clear();
StringSource(iv, sizeof(iv), true, new HexEncoder(new StringSink(encoded)));
cout << "iv: " << encoded << endl;
cout << "Size of iv: " << sizeof(iv) << endl;
try {
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption e;
e.SetKeyWithIV(key, sizeof(key), iv);
CryptoPP::FileSource(inFile, true, new CryptoPP::StreamTransformationFilter(e, new CryptoPP::FileSink(outFile)));
inFile.close();
outFile.close();
}
catch (CryptoPP::Exception& e) {
errMsg = e.GetWhat();
return false;
}
return true;
}
输出:
key: 6574D7BDFD0DD3BC59CD3846D4A196A8
Size of key: 16
iv: 1B4ED692F91A32246B41F63F6B8C6EAA
Size of iv: 16
key: 6574D7BDFD0DD3BC
Size of key: 8
iv: 1B4ED692F91A3224
Size of iv: 8
最佳答案
不,你不知道。您创建的对象具有 automatic storage duration ,这意味着它们的析构函数将在其作用域结束时自动调用。此外,您通过 new
传递的参数将归 Crypto++ 对象所有,它们相应的析构函数将为您释放内存。它们属于sink 或filter 类别,事实证明您也传递了所有权。有关详细信息,请参阅:
https://www.cryptopp.com/wiki/Pipelining#Ownership
基本上是这样的( super 简化的例子):
#include <iostream>
struct Foo{};
class X
{
Foo *p_;
public:
X(Foo* p): p_(p) {}
// we'd also need a copy ctor and copy assignment operator, ignored here
~X()
{
std::cout << "Releasing the memory...\n";
delete p_;
}
};
int main()
{
X x(new Foo()); // sinking, no memory leak
}
我不得不说,这是迄今为止我最不喜欢的软件设计风格。人们可以使用模板和混入来实现类似的事情(阅读关于 policy based design 的内容),而无需指针在没有明确所有权的情况下四处 float 。
关于c++ - 加密/解密期间 Crypto++ 显式销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545105/