【问题标题】:'message hash or MAC not valid' exception after decryption解密后出现“消息哈希或 MAC 无效”异常
【发布时间】:2015-09-05 08:04:53
【问题描述】:

我正在尝试制作一个使用 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 我已经浏览了以下答案

How to read an image to a string for encrypting Crypto++

How to loop over Blowfish Crypto++

【问题讨论】:

标签: c++ encryption cryptography crypto++


【解决方案1】:

当您尝试设置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));

通过我测试的代码如上。

【讨论】:

  • 是的,你是对的。所以,我在 MAC 上调试后更新了我的答案。当我尝试构建 libcrypto 时,我提到了您以前关于 Installing Crypto++ 5.6.2 on Mac OS X 的答案之一。谢谢。
  • 很好,埃里克。我修复了 wiki,所以它不再显示 decryptor.SetKeyWithIV(...);。现在它像上面一样调用它以避免复制/粘贴错误。
  • 我猜这个错误毕竟是在算法的实现中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2016-03-23
相关资源
最近更新 更多