我正在尝试制作一个使用 crypto++ 库加密文件(.jpg 和 .avi)的程序。我的目标是制作一个使用 AES-256 成功加密视频文件的程序。
我从 here 中做了 AES 加密的文本示例并且它们运行成功(意味着库设置正确)。但是,下面的简单代码会产生异常
HashVerificationFilter: message hash or MAC not valid
代码:
AutoSeededRandomPool prng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock(key, key.size());
SecByteBlock iv(AES::BLOCKSIZE);
prng.GenerateBlock(iv, iv.size());
string ofilename = "testimage.png";
string efilename;
string rfilename = "testimagerecovered.png";
try
{
GCM< AES >::Encryption e;
e.SetKeyWithIV(key, key.size(), iv, iv.size());
ifstream ofile(ofilename.c_str(), ios::binary);
ofile.seekg(0, ios_base::beg);
FileSource fs1(ofilename.c_str(), true,
new AuthenticatedEncryptionFilter(e,
new StringSink(efilename)));
GCM< AES >::Decryption d2;
d2.SetKeyWithIV(key, key.size(), iv, sizeof(iv));
StringSource fs2(efilename, true,
new AuthenticatedDecryptionFilter( d2,
new FileSink (rfilename.c_str()),
AuthenticatedDecryptionFilter::THROW_EXCEPTION));
}
catch(const Exception &e)
{
cerr << e.what() << endl;
exit(1);
}
return 0;
我怀疑我没有正确实现 AES 算法。但是,最近两天我找不到解决方案。我在 Ubuntu 14.04 上使用 Eclipse Luna。
PS 我已经完成了以下答案
最佳答案
当您尝试设置d2.SetKeyWithIV
时,请使用iv.size()
而不是sizeof(iv)
,就像您所做的一样已完成 e.SetKeyWithIV
。
因为在这个程序中,iv.size()
的值是16,但是sizeof(iv)
是24。然后就可以了。
GCM< AES >::Decryption d2;
d2.SetKeyWithIV(key, key.size(), iv, iv.size()); //here was a misuse of sizeof(iv)
StringSource fs2(efilename, true,
new AuthenticatedDecryptionFilter( d2,
new FileSink (rfilename.c_str()),
AuthenticatedDecryptionFilter::THROW_EXCEPTION));
我测试通过的代码如上。
关于c++ - 解密后出现“消息哈希或 MAC 无效”异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30936448/