我要做的是
openssl的MD5 function from the crypto library函数(以及它的许多其他散列函数)返回一个unsigned char
数组。我正试图从这个数组中获取哈希字符串。
例子:
数组:
{126, 113, 177, 57, 8, 169, 240, 118, 60, 10, 229, 74, 249, 6, 32, 128}
搞砸:
7e71b13908a9f0763c0ae54af9062080
数组中的每个数字都表示为两个十六进制数字。哈希字符串的长度是数组长度的两倍。
我所拥有的
请查看完整代码here。这是其中的一部分。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define nu 0
typedef struct {
int len;
unsigned char *Hash;
}Type;
Type test[6];
int main(void) {
unsigned char XUzQ[16]={
126, 113, 177, 57, 8, 169, 240, 118, 60, 10, 229, 74, 249, 6, 32, 128
};
test[0].len=16; test[0].Hash=XUzQ;
int h;
const char *hex="0123456789abcdef";
char *Ha=calloc(test[nu].len*2+1,sizeof(char));
for (h=0;h<test[nu].len;++h) {
*(++Ha)=hex[(test[nu].Hash[h]/16)%16];
*(++Ha)=hex[test[nu].Hash[h]%16];
}
Ha-=(test[nu].len*2-1);
if (strlen(Ha)==(test[nu].len*2))
printf("'%s'\n",Ha);
else puts("Failed!");
Ha--;
free(Ha);
return 0;
}
这打印了我期望的值(
7e71b13908a9f0763c0ae54af9062080
),但在我看来,同样的事情可以更好更快地实现。笔记
我使用的数组的名称非常奇怪,因为它们是由python脚本使用随机字符自动生成的。
test
是一个这么大的数组(请单击上面的链接查看我的完整代码)。问题
我怎样才能更快更容易地达到同样的结果呢?如果解决方案支持openssl支持的所有散列算法,我将不胜感激。
最佳答案
您可以使用snprintf
,尽管您现有的解决方案可能更快:
char* to_hex_string(const unsigned char h[16]) {
char* out = malloc(33);
size_t l =
snprintf(out, 33,
"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7],
h[8], h[9], h[10], h[11], h[12], h[13], h[14], h[15]);
assert(l == 32);
return out;
}
或者,对于使用sprintf的更通用的解决方案:
void byte_to_02x(char out[3], unsigned char byte) {
assert(snprintf(out, 3, "%02x", byte) == 2);
}
char* bytevector_to_hexstring(unsigned char* bytes, size_t n) {
char* out = malloc(2*n + 1);
for (int i = 0; i < n; ++i)
assert(snprintf(&out[2*i], 3, "%02x", bytes[i]);
return out;
}