Creating a HMAC 256 in C++ using the cryptopp library

QuestionsCategory: QuestionsCreating a HMAC 256 in C++ using the cryptopp library
Brightn-n-Fresh Staff asked 1 year ago

I am new to c++ and cryptography, so here it goes:

I have a string which I need to encode in HMAC 256 using C++ cryptopp. The code from the library wiki:

AutoSeededRandomPool prng;
SecByteBlock key(16);
prng.GenerateBlock(key, key.size());

string plain = "HMAC Test";
string mac, encoded;

/*********************************\
\*********************************/

// Pretty print key
encoded.clear();
StringSource ss1(key, key.size(), true,
    new HexEncoder(
        new StringSink(encoded)
    ) // HexEncoder
); // StringSource

cout << "key: " << encoded << endl;
cout << "plain text: " << plain << endl;

/*********************************\
\*********************************/

try
{
    HMAC< SHA256 > hmac(key, key.size());

    StringSource ss2(plain, true, 
        new HashFilter(hmac,
            new StringSink(mac)
        ) // HashFilter      
    ); // StringSource
}
catch(const CryptoPP::Exception& e)
{
    cerr << e.what() << endl;
    exit(1);
}

/*********************************\
\*********************************/

// Pretty print
encoded.clear();
StringSource ss3(mac, true,
    new HexEncoder(
        new StringSink(encoded)
    ) // HexEncoder
); // StringSource

cout << "hmac: " << encoded << endl;

The example provide works, but seems to do a hell of a lot. All I am trying to do is:

  1. Take a string: "GreatWallOfChina"
  2. key: m2hspk1ZxsjlsDU6JhMvD3TQQhm+zOwab3slKEILoSSnfk3b2+NUyeJiCrRAJ/D3V5y+QDZaIqRx9q9siMopaA==
  3. Convert key to base64: bTJoc3BrMVp4c2psc0RVNkpoTXZEM1RRUWhtK3pPd2FiM3NsS0VJTG9TU25mazNiMitOVXllSmlDclJBSi9EM1Y1eStRRFphSXFSeDlxOXNpTW9wYUE9PQ==
  4. Using that base64 key to create a hmac256.

So, my question is, are all the steps in the example code above necessary? (Byte block declarations, Hex encoding etc) Apologies if this is a very noobish question.

(177)