I have this code:
string HMACsha256(string message, string APIkey){
// The secret key for hashing
char key[APIkey.length() + 1];
strcpy(key, APIkey.c_str());
// The data that we're going to hash
char data[message.length() + 1];
strcpy(data, message.c_str());
unsigned char* result;
unsigned int len = 64;
result = (unsigned char*)malloc(sizeof(char) * len);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha256(), NULL);
HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));
HMAC_Final(&ctx, result, &len);
HMAC_CTX_cleanup(&ctx);
printf("HMAC digest: ");
string signature; // <-------- I want to store the values from the printf with result in the loop below in this
for (int i = 0; i != len; i++){
printf("%02x", (unsigned int)result[i]); //<--- I want this in signature string
}
cout << endl<< "SIG: " << signature << endl;
free(result);
return signature;
}
Everything about it works fine, except I need to be able to return the result as a string. I've been unable to come up with a way to take the hex data from the unsigned char* result variable and store it into the signature string. Does anyone know how I can go about this?
EDIT: This question was flagged as a duplicate of convert a char* to std::string However, I have already tried the excepted answer on that thread of doing
const char *s = "Hello, World!";
std::string str(s);
With my code it looks like:
string signature(result);
Running my code like that produces this error:
error: no matching constructor for initialization of 'string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
string signature(result);
With
string signature(reinterpret_cast<char*>(result));
The results are:
Result:
20ef96358c199befc0a0e6de47170734532e48e7ddfbf4ea48ef207989342677
Signature:
?5???????G4S.H?????H? y?4&w?Ήf?
It's been brought to my attention that I "don't want to convert the data to string as is, but rather a hexadecimal representation" if that makes this question more clear for anyone.