c++ - 带有 GunZip 的 AES/GCM,无法正确解压

标签 c++ qt encryption crypto++ aes-gcm

编辑 我再次改写了这个问题并提供了一个可以重现错误的最小工作示例。

我正在尝试使用 GCM 进行文件加密。我的下划线框架是Qt。思路是这样的:

  1. 加载源文件,例如一个.jpg
  2. 在GCM模式下将文件加密为PDATA
  3. 进入 ADATA 存储单字节(目前,在实际应用中,这将更多地包含 IV、原始文件名等信息)
  4. 将 ADATA 附加到加密文件

  5. 加载加密文件并提取ADATA/PDATA/MAC

  6. 以正确的顺序将此数据提供给 AuthenticatedDecryptionFilter 并期望将解密的文件存储到 FileSink

我需要一个遍历未加密文件并将文件泵入 AuthenticatedEncryptionFilter 的循环,因为我需要在实际应用程序中检查 isAlive 以实现线程目的。因此,我不能使用简单的流水线,而必须在循环中手动处理数据。

现在解决问题

以下代码的哈希验证失败(derypt 抛出异常)

#include <qdebug.h>
#include <CryptoPP/cryptlib.h>
#include <CryptoPP/gcm.h>
#include <CryptoPP/aes.h>
#include <CryptoPP/filters.h>
#include <CryptoPP/files.h>
#include <CryptoPP/gzip.h>
#include <qfile.h>
#include <qfileinfo.h>


using namespace CryptoPP;
using namespace std;
int main(int argc, char *argv[])
{

    byte * key = new byte[16];
    byte * iv = new byte[16];

    memset(key, 0, 16);
    memset(iv, 0, 16);

    const int TAG_SIZE = 16;
    const int BUFFER_SIZE = 4096;

    byte keyLength = 16;
    byte blockSize = 16;

    const char * sourceFileName = "C:\\Users\\Tomas\\Documents\\Visual Studio 2013\\Projects\\testgcm\\Win32\\Debug\\source.jpg";
    const char * sourceFileName2 = "C:\\Users\\Tomas\\Documents\\Visual Studio 2013\\Projects\\testgcm\\Win32\\Debug\\source2.jpg";
    const char * destFileName = "C:\\Users\\Tomas\\Documents\\Visual Studio 2013\\Projects\\testgcm\\Win32\\Debug\\source.jpg.enc";


    try
    {

        GCM< AES >::Encryption e;
        e.SetKeyWithIV(key, keyLength, iv, blockSize);

        AuthenticatedEncryptionFilter ef(e,
            new FileSink(destFileName), false, TAG_SIZE
            ); 

        // AuthenticatedEncryptionFilter::ChannelPut
        //  defines two channels: "" (empty) and "AAD"
        //   channel "" is encrypted and authenticated
        //   channel "AAD" is authenticated


        // this is the block for ADATA
        QByteArray adata;
        adata.append((char)1);

        ef.ChannelPut("AAD", (const byte *)adata.data(), adata.size());
        ef.ChannelMessageEnd("AAD");

        FileStore fs(sourceFileName);

        int mr = 0;

        while (mr = fs.MaxRetrievable()){
            fs.TransferTo(ef, BUFFER_SIZE,"");
        }

        ef.ChannelMessageEnd("");

        // append ADATA to encrypted file

        QFile file(QString::fromStdString(destFileName));
        file.open(QIODevice::Append);

        file.write(adata);

        file.close();

        // HELP: is the encrypted file in this format now? ENC_TEXT||MAC(TAG_SIZE)||HEADER(1)


    }
    catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)
    {
        // The tag must go in to the default channel:
        //  "unknown: this object doesn't support multiple channels"
        cerr << "Caught NoChannelSupport..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }
    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
    {
        // Pushing PDATA before ADATA results in:
        //  "GMC/AES: Update was called before State_IVSet"
        cerr << "Caught BadState..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }
    catch (CryptoPP::InvalidArgument& e)
    {
        cerr << "Caught InvalidArgument..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }

    // DECRYPTION


    try
    {

        // now extract ADATA and MAC from enc file
        QFile file(QString::fromStdString(destFileName));
        file.open(QIODevice::ReadOnly);
        file.seek(file.size() - 1);

        // ADATA
        QByteArray adata = file.read(1);

        // exract MAC

        file.seek(file.size() - 1 - TAG_SIZE);
        QByteArray mac = file.read(TAG_SIZE);

        GCM< AES >::Decryption d;
        d.SetKeyWithIV(key, keyLength, iv);


        // Object will not throw an exception
        //  during decryption\verification _if_
        //  verification fails.

        AuthenticatedDecryptionFilter df(d, new FileSink(sourceFileName2),
            AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
            AuthenticatedDecryptionFilter::THROW_EXCEPTION, TAG_SIZE);


        df.ChannelPut("", (const byte*)mac.data(), mac.size());

        // The order of the following calls are important
        df.ChannelPut("AAD", (const byte*)adata.data(), adata.size());

        // open enc file
        FileStore fs(destFileName);


        // when we read the file, we dont care for the ADATA and TAG, so we omit it
        int omitSize = (adata.size() + mac.size());

        // max retrievable (for FileStore this is how many bytes are not read yet)
        int mr = 0;

        // get part without tag and footer
        while (((mr = fs.MaxRetrievable()) > omitSize)){
            mr = ((mr - omitSize) < BUFFER_SIZE) ? (mr - omitSize) : BUFFER_SIZE;
            fs.TransferTo(df, mr, "");
        }

        // we pumped teh whole filestore into df. it was supposed to be pumping it to GUnzip and then to FileSink

        // and signal this is all
        df.ChannelMessageEnd("AAD");
        df.ChannelMessageEnd("");


    }
    catch (CryptoPP::InvalidArgument& e)
    {
        cerr << "Caught InvalidArgument..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }
    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
    {
        // Pushing PDATA before ADATA results in:
        //  "GMC/AES: Update was called before State_IVSet"
        cerr << "Caught BadState..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }
    catch (CryptoPP::HashVerificationFilter::HashVerificationFailed& e)
    {
        cerr << "Caught HashVerificationFailed..." << endl;
        cerr << e.what() << endl;
        cerr << endl;
    }




}

我怀疑我以错误的方式将信息输入解密器,但我正在关注 official CryptoPP example .

请帮忙, 谢谢

最佳答案

这最终是微不足道的。始终确保将 ivSize 传递给

GCM< AES >::Decryption d;
d.SetKeyWithIV(key, keyLength, iv, blockSize);

 GCM< AES >::Encryption e;
 e.SetKeyWithIV(key, keyLength, iv, blockSize);

尽管它们是可选的。否则会导致解密不正确

关于c++ - 带有 GunZip 的 AES/GCM,无法正确解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006008/

相关文章:

c++ - 使用 Qt 测试本地连接

qt - QSortFilterProxyModel 并按整数、 bool 值过滤

凯撒密码 C 程序无法运行

c++ - C++ 是否支持 'finally' block ? (我一直听到的这个 'RAII' 是什么?)

c++ - 我应该如何在游戏中存储和使用枪支开火数据?

c++ - 检索作为 QLineEdit 小部件的 QTableWidget 单元格的值

php - PHP 5.5 的 Ioncube 难度

javascript - Node.js 中的 PHP aes-256-cbc mcrypt_decrypt() 等价物

C++ - 继承,调用哪个基本构造函数?

c++ - clang-format 可以在列中对齐变量或宏赋值吗?