“消息散列或MAC无效”解密后的异常 [英] 'message hash or MAC not valid' exception after decryption

查看:280
本文介绍了“消息散列或MAC无效”解密后的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用加密++库来加密文件(.jpg和.avi)的程序。我的目标是使用AES-256成功加密视频文件的程序。

I'm trying to make a program that encrypts files (.jpg and .avi) using the crypto++ libraries. My aim is to make a program that successfully encrypts video files using AES-256.

我从这里,并且它们成功运行(意味着库的设置正确)。但是,以下简单代码产生异常

I did text examples of AES encryption from here and they ran successfully (meaning that the library is setup correctly). However, the following simple code produces the exception

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。

I suspect I am not implementing the AES algorithm correctly. However, I am unable to find a solution for the last two days. I'm using Eclipse Luna on Ubuntu 14.04.

PS我已经通过以下答案

PS I have gone through the following answers

如何将图像读取到字符串加密Crypto ++

如何循环Blowfish Crypto ++

推荐答案

请使用 iv.size()而不是 sizeof(iv)当您尝试设置 d2.SetKeyWithIV ,就像您所做的一样到 e.SetKeyWithIV
因为在这个程序中, iv.size()的值是16,而是 sizeof(iv)

Please use iv.size() rather than sizeof(iv) when you try to set d2.SetKeyWithIV, just like what you have done to e.SetKeyWithIV. Because in this program, the value of iv.size() is 16, but sizeof(iv) is 24. Then it will work.

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));

通过我测试的代码如上。

The code which has passed my test is as above.

这篇关于“消息散列或MAC无效”解密后的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆