Search code examples
c++cryptographycrypto++

HashVerificationFilter and "message hash or MAC not valid" exception


In Crpto++ one can easily use pipeline to hash an input.

std::string out;
CryptoPP::SHA256 sha;
CryptoPP::StringSource ss(input,true,
                          new CryptoPP::HashFilter(sha,
                              new CryptoPP::HexEncoder(
                                  new CryptoPP::StringSink(out))));

Now inorder to verify a gives message x produces the same hash output, I would like to use HashVerificationFilter. I have tried it but it doesn't work. Anyone know the correct syntax ?

const int flags = CryptoPP::HashVerificationFilter::THROW_EXCEPTION | CryptoPP::HashVerificationFilter::HASH_AT_END;
CryptoPP::SHA256 sha;
try
{
    CryptoPP::StringSource ss(input + out, true,
                              new CryptoPP::HashVerificationFilter(sha, NULL , flags));
}
catch(const CryptoPP::Exception& e)
{
    std::cerr << e.what() << std::endl;
    exit(1);
}

I get the output :

HashVerificationFilter: message hash or MAC not valid

Solution

  • std::string out;
    SHA256 sha;
    StringSource ss(input,true,
        new HashFilter(sha,
            new HexEncoder(
                new StringSink(out)
    )));
    

    You HexEncode your hash. You need to decode it before passing it to the filter:

    StringSource ss(input + out, true,
        new HashVerificationFilter(sha, NULL , flags)
    );
    

    Or, remove the encoding filter:

    std::string out;
    SHA256 sha;
    StringSource ss(input,true,
        new HashFilter(sha,
            new StringSink(out)
    ));