I have a string which I need to encode in HMAC 256 using C++ and Crypto++. 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:
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.
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.