我有这段代码可以生成带有 SHA384 哈希的 HMAC。它使用 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]);
因此,如您所见,散列存储在 result
数组中。 printf
循环用于打印数组中的每个单元,并将其转换为十六进制。
我需要将打印的十六进制字符串存储在 char
变量中。我怎样才能做到这一点?提前致谢!
最佳答案
1st 分配整个散列的“字符串”表示所需的空间:
从 C99 开始,这可以使用 VLA 完成:
char str[2*len + 1] = "";
或者动态分配:
char * str = calloc(2*len + 1, sizeof(*str));
然后使用sprintf()
获取单个字节的表示并连接它们:
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);
}
如果使用了动态分配,不要忘记释放分配给 s
的内存(如果不再需要的话):
free(str);
关于c - 将十六进制格式的整数数组保存到 char "string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127523/