gpt4 book ai didi

c - openssl/sha.h 似乎计算出了错误的哈希值

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:26 24 4
gpt4 key购买 nike

我正在尝试计算 C 中给定字符串的 SHA1 值。我正在通过 #include <openssl/sha.h> 使用 OpenSSL 库。 .该程序的相关部分如下。 但它不应该引起任何问题。

void checkHash(char* tempString) {
unsigned char testHash[SHA_DIGEST_LENGTH];
unsigned char* sha1String = (unsigned char*)tempString;
SHA1(sha1String, sizeof(sha1String), testHash);
printf("String: %s\nActual hash: 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8\nComputed hash: ", tempString);
// I verified the actual hash for "a" using multiple online hash generators.
for (i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%x", testHash[i]);
printf("\n");
}

使用 checkHash("a"); 运行程序产生以下输出:

String: a
Actual hash: 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8
Computed hash: 16fac7d269b6674eda4d9cafee21bb486556527c

为什么这些哈希值不匹配?我在 64 位 Windows 7 机器上的 64 位 Linux VM 中运行。这在过去给我带来了一些散列实现不佳的问题,但我怀疑这是使用 OpenSSL 版本的问题。

最佳答案

sizeof(sha1string)sizeof(unsigned char*) 相同,即数据指针的大小。你想在那里传递字符串的长度,使用 strlen 而不是 sizeof,否则你不会散列你认为你正在散列的东西。

如果tempString不是空字符结尾的字符串而是任意数据,需要将数据的长度传入checkHash,这就没办法了从该函数中判断长度。

关于c - openssl/sha.h 似乎计算出了错误的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20458420/

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