gpt4 book ai didi

c - 如何将数组转换为散列?

转载 作者:太空狗 更新时间:2023-10-29 15:40:35 25 4
gpt4 key购买 nike

我想做什么


OpenSSL 的 MD5 function from the crypto library(以及它的许多其他哈希函数)返回一个 unsigned char 数组。 我正在尝试从此数组中获取哈希字符串。

例子:

Array:

{126, 113, 177, 57, 8, 169, 240, 118, 60, 10, 229, 74, 249, 6, 32, 128}

Hash:

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;
}

关于c - 如何将数组转换为散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com