【问题标题】:OpenSSL hash of a file is the same in C文件的 OpenSSL 哈希在 C 中是相同的
【发布时间】:2020-11-03 00:41:12
【问题描述】:

我正在学习使用 OpenSSL 在 C 中对文件进行哈希处理,但我总是得到相同的哈希值。我尝试了不同的文件和内容,但哈希没有改变。如果我使用不同的文件,它应该显示不同的哈希值。我不确定问题出在哪里。

这是我的代码:

#include <openssl/sha.h>
#include <stdio.h>
#include <fcntl.h>

#define BUFF_SIZE 256

int main(int argc, char* argv[]) {
   int fd;
   char buff[BUFF_SIZE];
   int i = 0;

   SHA_CTX sha_ctx;
   unsigned char sha_hash[SHA_DIGEST_LENGTH];

   SHA1_Init(&sha_ctx);

   fd = open(argv[1], O_RDONLY, 0);
   do {
      i = read(fd, buff, i);
      SHA1_Update(&sha_ctx, buff, i);
   } while(i > 0);
   close(fd);

   SHA1_Final(sha_hash, &sha_ctx);

   printf("\n Hash of the file: %s \n\n", argv[1]);
   for(i = 0; i < SHA_DIGEST_LENGTH; ++i) {
      printf("%x", sha_hash[i]);
   }
   printf("\n\n");
   return 0;
}

这样编译

gcc -g hash.c -lcrypto

【问题讨论】:

  • 在您发布的代码中,您没有检查函数调用 openread 的返回值是否失败。你有没有检查过这些功能是否失败了?

标签: c file hash openssl cryptography


【解决方案1】:

我认为你的问题就在这里:

i = read(fd, buff, i);

i 被初始化为零,所以你告诉read() 最多读取 0 个字符。相反,您应该指定缓冲区大小:

i = read(fd, buff, BUFF_SIZE);

我还建议您向 openread 调用添加错误检查,正如 Andreas Wenzel 的评论所建议的那样。检查您的 argc 以确保您也获得了预期的命令行参数数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2021-10-25
    相关资源
    最近更新 更多