将十六进制格式的整数数组保存为char";“字符串”;
我有一段代码,它生成了一个带有SHA384散列的HMAC。它使用将十六进制格式的整数数组保存为char";“字符串”;,c,hex,C,Hex,我有一段代码,它生成了一个带有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)); HMA
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
变量中。我该怎么做?提前谢谢 1分配整个哈希的“字符串”表示所需的空间:
- 从C99开始,这可以使用VLA完成:
char str[2*len + 1] = "";
- 或者动态分配:
char * str = calloc(2*len + 1, sizeof(*str));
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);
}
sprintf已经试过了,但不起作用。我可能做错了什么,你能写个例子吗?
calloc()
需要两个参数。第二个是什么?@jndok:Fixed。谢谢
free(str);