LeeO LeeO - 2 months ago 19
C++ Question

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

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.

Answer

No, your steps above are certainly not necessary, such as base 64 encoding an already base 64 encoded value.

Crypto++ is mainly based on streaming with sinks and sources. That's just the way the library is set up, but for small calculations it will be somewhat verbose.

Note that most of the sample code is simply key generation and printing out the plaintext, key and authentication tag (MAC value) and some exception handling. The required code is just within the try / catch block basically.