比较 c 中的哈希值

标签 c hash sha256

我正在尝试比较和匹配哈希:

#include <stdio.h>
#include <string.h>
#include "sha256.h"

int main()
{
   unsigned char password[]={"abc"}, gen_hash[32];
   SHA256_CTX ctx;

   sha256_init(&ctx);
   sha256_update(&ctx,password,strlen(password));
   sha256_final(&ctx,gen_hash);

   unsigned char orig_hash[] = {"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"};

   if(strcmp(orig_hash, gen_hash) == 0)
   {
    printf("%s\n", "match");
   }
   return 0;
}

但是如果我比较两个哈希值,它们是不一样的。有没有人碰巧知道为什么?我以为这两个变量是相同的,但它们不是吗?

最佳答案

两点:

  1. 不要使用 strcmp,而是使用 memcmp,因为生成的散列 gen_hash 不会有 '\0'结束。

  2. 您将 orig_hash 定义为

    unsigned char orig_hash[] = {"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"};

这是一串字符。您应该将其定义为数字数组:

unsigned char orig_hash[] = {0xba, 0x78, 0x16, 0xbf, ...};

关于比较 c 中的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37193767/

相关文章:

C# 返回值 SHA256Managed 为 NULL

c - 为什么在尝试 "cat"我的字符设备驱动程序时收到错误消息?

c# - 在 C# 中将 char * 编码到 StringBuilder

c - 在某些字符串的末尾获取垃圾值

ruby - 使用 `Hash#fetch` 优于 `Hash#[]` 的好处

循环插入后 C Glib 哈希不匹配?

java - 计算多部分数据(多个字符串)的 md5 散列

c++ - C/C++ memcpu 基准测试 : measuring CPU and wall time

swift - 如何在 swift 中使用 SHA256 和盐(一些 key )

python - SHA 256 不同的结果