Reputation: 33
I'm trying code a openssl HMAC SHA512 encryption but i compare my result with some online pages such HMAC-SHA256 Online Generator Tool and the result is not the same I can not figure out what i'm doing wrong, its my first time coding c++ with openssl encryption.
this is my code until now:
char *key = "apiPrivateKey";
const unsigned char data[512] = "message";
int data_len = sha512HashData.size();
unsigned char hmac[128];
for (int i = 0; i < 128; i++)
{
hmac[i]= 0;
}
char outputBuffer[128];
for (int i = 0; i < 128; i++)
{
outputBuffer[i]= 0;
}
unsigned int len = EVP_MAX_MD_SIZE;
std::vector<unsigned char> digest(len);
HMAC_CTX *ctx;
unsigned int res_len;
ctx = HMAC_CTX_new();
HMAC_Init_ex(ctx, key, strlen((const char*)key), EVP_sha512(), NULL);
HMAC_Update(ctx, data, data_len);
HMAC_Final(ctx, hmac, &res_len);
HMAC_CTX_free(ctx);
int i = 0;
for(i = 0; i < 128; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hmac[i]);
}
//https://stackoverflow.com/a/1195705/11632453
std::string myString;
myString.assign(outputBuffer, 128);
std::cout << "ComputeHMAC512Hash: " << myString << std::endl;
return myString;
Any suggestions? thanks
Upvotes: 1
Views: 1358
Reputation: 6546
Don't know how to debug your code, here's a working one.
std::string b2a_hex(const std::uint8_t* p, std::size_t n) {
static const char hex[] = "0123456789abcdef";
std::string res;
res.reserve(n * 2);
for (auto end = p + n; p != end; ++p) {
const std::uint8_t v = (*p);
res += hex[(v >> 4) & 0x0F];
res += hex[v & 0x0F];
}
return res;
}
std::string hmac_sha512(const char* key, std::size_t klen, const char* data, std::size_t dlen) {
std::uint8_t digest[EVP_MAX_MD_SIZE];
std::uint32_t dilen{};
auto p = ::HMAC(
::EVP_sha512()
, key
, klen
, (std::uint8_t*)data
, dlen
, digest
, &dilen
);
assert(p);
return b2a_hex(digest, dilen);
}
::HMAC is from openssl library
Upvotes: 1