简体   繁体   中英

HMAC-SHA256 in C with OpenSSL - how to get a correct output

Here is the function I use to encode a string:

#include <openssl/evp.h>
#include <openssl/hmac.h>

unsigned char *mx_hmac_sha256(const void *key, int keylen,
                              const unsigned char *data, int datalen,
                              unsigned char *result, unsigned int *resultlen) {
    return HMAC(EVP_sha256(), key, keylen, data, datalen, result, resultlen);
}

Here is how I call it and check the result:

char *key = strdup("security is awesome");
int keylen = strlen(key);
const unsigned char *data = (const unsigned char *)strdup("this is highly sensitive user data");
int datalen = strlen((char *)data);
unsigned char *result = NULL;
unsigned int resultlen = -1;

result = mx_hmac_sha256((const void *)key, keylen, data, datalen, result, &resultlen);

for (unsigned int i = 0; i < resultlen; i++) 
    printf("%c", result[i]);

printf("\n");
for (unsigned int i = 0; i < resultlen; i++) 
    printf("%u ", result[i]);

printf("\nencrypted: %s   len = %d\n", result, resultlen);

Here's the output (junk) I get:

�����չm�yk'�HH�T�,|�q��_��
204 219 230 247 135 213 185 109 186 121 107 39 234 72 72 17 234 84 229 44 124 242 113 241 172 190 199 95 205 201 16 18 
encrypted: �����չm�yk'�HH�T�,|�q��_��.  len = 32

This is the hash I get when I input the same strings into an online HMAC Generator:

ccdbe6f787d5b96dba796b27ea484811ea54e52c7cf271f1acbec75fcdc91012

在线生成 HMAC-SHA256

I'm struggling to figure out where it all went wrong. The mx_hmac_sha256 function I use is copy-pasted from StackOverflow, I checked the OpenSSL docs and they suggest exactly the same function but don't give much more guidance. Am I passing the variables incorrectly? Why is the key argument's type const void *, isn't it meant to be a string? Maybe strdup or strlen doesn't work with unsigned char *? Do I interpret the output the wrong way? I suspect the issue is about me handling the unsigned char * string incorrectly, but I've never dealt with them before and don't know where to look for the mistake. Any suggestions are very welcome

You are getting the same result, you are just printing it as decimals whereas the online tool is outputting hexadecimal.

204 decimal is CC in hecadecimal, 219 is DB etc.

Try

for (unsigned int i = 0; i < resultlen; i++){
  printf("%02hhX", result[i]); // or just "%02X" if you are not using C11 or later
}

instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM