c++ - 解密后出现“消息哈希或 MAC 无效”异常

标签 c++ encryption cryptography crypto++

我正在尝试制作一个使用 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++

最佳答案

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

相关文章:

ios - 分块解密媒体文件并通过 AVPlayer 播放

c++ - 获取当前进程中加载​​的 DLL 列表及其引用计数

Java AES加密/解密始终返回相同的内容

git - git history 是否会破坏使用 OpenSSL 加密的文件?

iOS:存储在安全区域中的 key 不支持解密

c# - 我的解密密码是 1 个字符

android - 本地 iOS/Android key 存储是否已备份并且可以转移?

c++ - 结构错误 : Not recognized even though it is included

c++ - 里面有结构的类.. C++

c++ - 使用自定义比较器排序时出现运行时错误