Question

I have this code which generates an HMAC with a SHA384 hash. It uses openssl.

HMAC_CTX ctx;
HMAC_CTX_init(&ctx);

HMAC_Init_ex(&ctx, api_secret, (int)strlen(api_secret), EVP_sha384(), NULL);
HMAC_Update(&ctx, (unsigned char*)&encoded_payload, strlen(encoded_payload));
HMAC_Final(&ctx, result, &len);
HMAC_CTX_cleanup(&ctx);

for (int i = 0; i != len; i++)
    printf("%02x", (unsigned int)result[i]);

So, as you can see, the hash is stored inside the result array. The printf loop is used to print each single unit in the array, converted to hexadecimal.

I need to store the printed hexadecimal string in a char variable. How can i do this? Thanks in advance!

Was it helpful?

Solution

1st allocate the space needed for the whole hash's "string" representation:

  • From C99 on this could be done using a VLA:

    char str[2*len + 1] = "";
    
  • Or just allocate it dynamically:

    char * str = calloc(2*len + 1, sizeof(*str));
    

Then use sprintf() to get the single bytes' representions and just concatenate them:

for (size_t i = 0; i < len; ++i)
{
  char tmp[3];
  /* Use the hh length modifier, together with casting to a character to make sure to
     NOT overflow tmp. */
  sprintf(tmp, "%02hhx", (unsigned char) result[i]);
  strcat(str, tmp);
}

If having used dynamic allocation do not forget the free the memory allocated to s if not needed anymore:

free(str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top