0

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!

2
  • 1
    sprintf linux.die.net/man/3/sprintf Commented Mar 2, 2014 at 12:32
  • already tried, it doesn't work. I probably did something wrong, can you write an example? Commented Mar 2, 2014 at 12:39

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

calloc() needs two arguments. What's the second?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.