I was successfully able to get a HMAC_SHA1, however it is hex. I am not able to figure out how to get base64 string. This is how I get hex string:
Running this on "message" and "key" gives me hex string of 2088df74d5f2146b48146caf4965377e9d0be3a4
, this is correct. Doing a base64 encode on this gives me MjA4OGRmNzRkNWYyMTQ2YjQ4MTQ2Y2FmNDk2NTM3N2U5ZDBiZTNhNA==
, this is correctly base64 encoded, but not a b64 hash string, which should be IIjfdNXyFGtIFGyvSWU3fp0L46Q=
.
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
std::string calcHmac(std::string message, std::string key, std::string aStrType="base64") {
char hash[41];
// The data that we’re going to hash using HMAC
const unsigned char *unsignedData = (unsigned char *)message.c_str();
unsigned char *digest;
// I have used sha1 hash engine here.
digest = HMAC(EVP_sha1(), key.c_str(), strlen(key.c_str()), unsignedData, strlen((char *)unsignedData), NULL, NULL);
// Length of string depends on the chosen hash engine for example with the
// chosen hash engine i.e SHA1 it produces a 20-byte hash value which
// rendered as 40 characters.
// Length of the string need to be changed as per hash engine used.
for (int i = 0; i < 20; i++) {
sprintf(&hash[i * 2], "% 02x", (unsigned int)digest[i]);
}
std::string hash_hex = std::string(hash);
// if (aStrType == "base64") {
// std::string hash_b64 = "";
// return hash_b64;
// }
return hash_hex;
}