我成功获得了HMAC_SHA1,但它是十六进制的。我无法弄清楚如何获得base64字符串。这就是我得到十六进制字符串的方式:
在“message”和“key”上运行此命令会给我2088df74d5f2146b48146caf4965377e9d0be3a4
的十六进制字符串,这是正确的。对此进行base64编码可以得到MjA4OGRmNzRkNWYyMTQ2YjQ4MTQ2Y2FmNDk2NTM3N2U5ZDBiZTNhNA==
,这是正确的base64编码,但不是b64哈希字符串,应该是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;
}