【问题标题】:crypto++ aes GCM-AEAD decrypt throw exception hash or MAC not valid' in cppcpp中的crypto++ aes GCM-AEAD解密抛出异常哈希或MAC无效'
【发布时间】:2021-02-03 10:14:04
【问题描述】:

首先,我是C++的初学者

我尝试使用crypto++库在c++中加密和解密数据

我为此创建了自定义类

类:

#ifndef CRYPTODATA
#define CRYPTODATA
typedef unsigned char byte;
#include <iostream>
#include "stdafx.h"
#include "assert.h"
using std::cerr;
using std::cout;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;

#include "cryptopp/cryptlib.h"
using CryptoPP::AuthenticatedSymmetricCipher;
using CryptoPP::BufferedTransformation;

#include <string>
using std::string;

#include "cryptopp/filters.h"
using CryptoPP::AuthenticatedDecryptionFilter;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::StringSink;
using CryptoPP::StringSource;

#include "cryptopp/aes.h"
using CryptoPP::AES;

#include "cryptopp/gcm.h"
using CryptoPP::GCM;
using CryptoPP::GCM_TablesOption;
#include <string>
namespace CryptoData{
    class CryptoData{
    public:
        CryptoData(){
      
            std::string _key = "mohsensalamkojayikhoobikhosshhaa";
            std::string _iv = "mohsensalamk";
            std::copy(_key.begin(), _key.end(), this->key);
            std::copy(_iv.begin(), _iv.end(), this->iv);
            pad = (16, (char)0x00);
           
        }
        CryptoData(std::string _key, std::string _iv, std::string _pad):pad(_pad){
            std::copy(_key.begin(), _key.end(), this->key);
            std::copy(_iv.begin(), _iv.end(), this->iv);
            std::copy(_pad.begin(), _pad.end(), this->pad);
        }
        ~CryptoData() {

        }   
        std::string _encrypting(std::string _data){
            return this->encryptData(_data);
        }
        std::string _decrypting(std::string _data) {
            return this->decryptData(_data);
        }
        
    
    protected:
        std::string decryptData(std::string _data) {
            std::string radata, rpdata;
            try
            {
                GCM<AES>::Decryption d;
                d.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));
                
                string enc = cipher.substr(0, cipher.length() - TAG_SIZE);
                string mac = cipher.substr(cipher.length() - TAG_SIZE);
                assert(cipher.size() == enc.size() + mac.size());
                assert(enc.size() == pad.size());
                assert(TAG_SIZE == mac.size());
                radata = _data;
                AuthenticatedDecryptionFilter df(d, NULL,
                    AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
                    AuthenticatedDecryptionFilter::THROW_EXCEPTION,
                    TAG_SIZE);
                df.ChannelPut("", (const byte*)mac.data(), mac.size());
                df.ChannelPut("AAD", (const byte*)_data.data(), _data.size());
                df.ChannelPut("", (const byte*)enc.data(), enc.size());
                df.ChannelMessageEnd("AAD");
                df.ChannelMessageEnd("");
                bool b = false;
                b = df.GetLastResult();
                assert(true == b);

                string retrieved;
                size_t n = (size_t)-1;

                df.SetRetrievalChannel("");
                n = (size_t)df.MaxRetrievable();
                retrieved.resize(n);

                if (n > 0)
                {
                    df.Get((byte*)retrieved.data(), n);
                }
                rpdata = retrieved;
                printf("done6 \n");
                assert(rpdata == pad);

                cout << "its a decrypted data " << radata << " \n";
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::HashVerificationFilter::HashVerificationFailed& e)
            {
                cerr << "Caught HashVerificationFailed..." << endl;
                cerr << e.what() << endl;
            }
            return radata;
        }
        std::string encryptData(std::string _data){
            std::string encoded;
            try
            {    
                GCM<AES>::Encryption e;
                e.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

                AuthenticatedEncryptionFilter ef(e,
                    new StringSink(cipher), false, TAG_SIZE); // AuthenticatedEncryptionFilter
               
                ef.ChannelPut("AAD", (const byte*)_data.data(), _data.size());
                ef.ChannelMessageEnd("AAD");

                ef.ChannelPut("", (const byte*)pad.data(), pad.size());
                ef.ChannelMessageEnd("");
                
                // Pretty print
                StringSource(cipher, true,
                    new HexEncoder(new StringSink(encoded), true, 16, " "));
            }
            catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)
            {
                cerr << "Caught NoChannelSupport..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
              
            }
            return encoded;
        }
    private:
        byte key[32];
        byte iv[12];
        const int TAG_SIZE = 16;
        std::string cipher;
        std::string pad;
    };
}
#endif

我尝试使用以下代码对字符串进行加密和解密:

int __cdecl main(void)
{
    CryptoData::CryptoData crypt;
    std::string _myData = "mohsenjooooon:X";
    std::string _encrypted = crypt._encrypting(_myData);
    printf("its encrypted data: %p  \n", _encrypted);
    std::string _decData = crypt._decrypting(_encrypted);
    printf("its decrypted data: %p \n", _decData);
    return 0;

}

最后我得到了这个异常:

捕获的 HashVerificationFailed... HashVerificationFilter:消息哈希或 MAC 无效

感谢帮助,我的代码问题在哪里?

【问题讨论】:

  • delete &amp;key; - 不,不,不,不,不。不,您需要学习基础知识。获取a good book
  • @Devolus 嘿,谢谢你的回答,但没有
  • @molbdnilo 为什么不呢?这里我不叫破坏者!!
  • @MrHaydari 我不知道你的评论是什么意思。是什么让您想到应该使用delete 成员变量,或者您没有使用new 创建的任何东西?

标签: c++ c++11 crypto++


【解决方案1】:

我把错误的数据放到了错误的频道

固定:

#ifndef CRYPTODATA
#define CRYPTODATA
typedef unsigned char byte;
#include <iostream>
#include "stdafx.h"
#include "assert.h"
using std::cerr;
using std::cout;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;

#include "cryptopp/cryptlib.h"
using CryptoPP::AuthenticatedSymmetricCipher;
using CryptoPP::BufferedTransformation;

#include <string>
using std::string;

#include "cryptopp/filters.h"
using CryptoPP::AuthenticatedDecryptionFilter;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::StringSink;
using CryptoPP::StringSource;

#include "cryptopp/aes.h"
using CryptoPP::AES;

#include "cryptopp/gcm.h"
using CryptoPP::GCM;
using CryptoPP::GCM_TablesOption;
#include <string>
namespace CryptoData{
    class CryptoData{
    public:
        CryptoData(){
      
            std::string _key = "mohsensalamkojayikhoobikhosshhaa";
            std::string _iv = "mohsensalamk";
            std::copy(_key.begin(), _key.end(), this->key);
            std::copy(_iv.begin(), _iv.end(), this->iv);
            string pad(16, (char)0x00);
            authCode = pad;
            printf("default constractor call \n");
           
        }
        CryptoData(std::string _key, std::string _iv, std::string _pad):authCode(_pad){
            std::copy(_key.begin(), _key.end(), this->key);
            std::copy(_iv.begin(), _iv.end(), this->iv);
            printf("constractor call with args \n");
        }
        ~CryptoData() {
            printf("default destractur call \n");

        }   
        std::string _encrypting(std::string _data){
            return this->encryptData(_data);
        }
 
        std::string _decrypting(std::string _data) {
            return this->decryptData(_data);
        }
       
    
    protected:
        std::string decryptData(std::string _data) {
            std::string radata, rpdata;
            try
            {
                GCM<AES>::Decryption d;
                d.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));
                string enc = cipher.substr(0, cipher.length() - TAG_SIZE);
                string mac = cipher.substr(cipher.length() - TAG_SIZE);
                assert(cipher.size() == enc.size() + mac.size());
               // assert(enc.size() == _data.size());
                assert(TAG_SIZE == mac.size());
                radata = authCode;
                AuthenticatedDecryptionFilter df(d, NULL,
                    AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
                    AuthenticatedDecryptionFilter::THROW_EXCEPTION,
                    TAG_SIZE);
                df.ChannelPut("", (const byte*)mac.data(), mac.size());
                df.ChannelPut("AAD", (const byte*)authCode.data(), authCode.size());

                df.ChannelPut("", (const byte*)enc.data(), enc.size());
                df.ChannelMessageEnd("AAD");
                df.ChannelMessageEnd("");
                bool b = false;
                b = df.GetLastResult();
                assert(true == b);

                string retrieved;
                size_t n = (size_t)-1;

                df.SetRetrievalChannel("");
                n = (size_t)df.MaxRetrievable();
                retrieved.resize(n);

                if (n > 0)
                {
                    df.Get((byte*)retrieved.data(), n);
                }
                rpdata = retrieved;
                printf("done6 \n");
                //assert(rpdata == pad);

                cout << "its a decrypted data " << radata << " \n";
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::HashVerificationFilter::HashVerificationFailed& e)
            {
                cerr << "Caught HashVerificationFailed..." << endl;
                cerr << e.what() << endl;
            }
            return rpdata;
        }
        
        std::string encryptData(std::string _data){
            std::string encoded;
            try
            {    
                GCM<AES>::Encryption e;
                e.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

                AuthenticatedEncryptionFilter ef(e,
                    new StringSink(cipher), false, TAG_SIZE); // AuthenticatedEncryptionFilter
               
                ef.ChannelPut("AAD", (const byte*)authCode.data(), authCode.size());
                ef.ChannelMessageEnd("AAD");

                ef.ChannelPut("", (const byte*)_data.data(), _data.size());
                ef.ChannelMessageEnd("");
                
                // Pretty print
                StringSource(cipher, true,
                    new HexEncoder(new StringSink(encoded), true, 16, " "));
            }
            catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)
            {
                cerr << "Caught NoChannelSupport..." << endl;
            }
            catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)
            {
                cerr << "Caught BadState..." << endl;
            }
            catch (CryptoPP::InvalidArgument& e)
            {
                cerr << "Caught InvalidArgument..." << endl;
              
            }
            return encoded;
        }
    private:
        byte key[32];
        byte iv[12];
        const int TAG_SIZE = 16;
        std::string cipher;
        std::string authCode;
    };
}
#endif

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2020-05-24
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    相关资源
    最近更新 更多