Question

I used this link to create a SHA1 hash for any data using C++. But the output buffer from SHA1 call is an unsigned char*. I want to store the hexadecimal values i.e. the Message Digest values so that I can use them for other operations.

As those are unsigned char* it doesn't make sense in converting them to a string and then performing hexadecimal conversion. So I have to do the hex conversion and then store the values as a string or char*. How can I do this?

SHA1(ibuf, strlen(ibuf), obuf);
for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
Was it helpful?

Solution

To format to a char[], use snprintf:

char out[61]; //null terminator
for (i = 0; i < 20; i++) {
    snprintf(out+i*3, 4, "%02x ", obuf[i])
}

Edit: I see you've tagged your question C++. This is a purely C solution, mostly because I don't know C++.

We're using a max size of 4 because we need to include the null terminator in that count (by the function definition). We only move ahead by three specifically to overwrite the null terminator.

The extra space at the end is bound to happen based on our format string of "%02x ", but if we special-case the last element we can use a different format string of "%02x" to avoid that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top