gpt4 book ai didi

c - C 中的密码散列为字符串散列

转载 作者:行者123 更新时间:2023-11-30 16:36:13 25 4
gpt4 key购买 nike

如何用 C 语言创建一个简单的密码哈希函数?我知道有一个可用的标准库,crypt.h ,还有openssl/sha.h但这不会产生字符串。我尝试了不同的方法来打印 sha256 字符串,但该字符串与同一单词的其他 sha256 字符串不一样。

我在本网站的一个主题中找到了用于哈希到 sha256 的代码:

char input[] = "hello";
int length = sizeof(input);
SHA256_CTX context;
unsigned char md[SHA256_DIGEST_LENGTH];
SHA256_Init(&context);
SHA256_Update(&context, (unsigned char *)input, length);
SHA256_Final(md, &context);

printf("%02x\n", md); // every time different value: c94ce410, 46d384c0 ..
printf("sizeof md = %zu\n", sizeof(md));
int i;
for(i = 0; i <= sizeof(md); i++) {
printf("%02x", md[i]); // not a sha256..
printf("%u", md[i]); // only numeric, not correct..
}
printf("\n");

它生成的字符串是: f3aefe62965a91903610f0e23cc8a69d5b87cea6d28e75489b0d2ca02ed7993c62

但这不是 hello 的 sha256 字符串,因为它不被在线解密服务识别。我正在使用#include <openssl/sha.h>对于这个。

编辑:

正确设置:

int length = strlen(input);
int i;
for(i = 0; i < sizeof(md); i++) {
printf("%0x", md[i]);
//printf("%u", md[i]);
}
printf("\n");

现在生成了正确的 sha256 哈希字符串。

最佳答案

你的长度错误。 typedef 返回类型的长度,这里的字符数组以\0 结尾。您需要使用 strlen 来代替。

关于c - C 中的密码散列为字符串散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600002/

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