简体   繁体   English

一个文件的OpenSSL hash在C中是一样的

[英]OpenSSL hash of a file is the same in C

am learning to do the hash of a file in C using OpenSSL but I always get the same hash.我正在学习使用 OpenSSL 执行 C 中的文件的 hash 但我总是得到相同的 Z0800FCZ28294C359E45B I have tried different files and content but the hash do not change.我尝试了不同的文件和内容,但 hash 没有改变。 If i use different files it should show different hash.I am not sure where the problem is.如果我使用不同的文件,它应该显示不同的 hash。我不确定问题出在哪里。

This is my code:这是我的代码:

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

Compile like this像这样编译

gcc -g hash.c -lcrypto

I think your problem is right here:我认为你的问题就在这里:

i = read(fd, buff, i);

i is initialized to zero, so you're telling read() to read at most 0 characters. i初始化为零,因此您告诉read()最多读取 0 个字符。 Instead, you should specify your buffer size:相反,您应该指定缓冲区大小:

i = read(fd, buff, BUFF_SIZE);

I also recommend you add error checks to open and read calls, as the comment by Andreas Wenzel suggests.正如 Andreas Wenzel 的评论所建议的那样,我还建议您添加错误检查来openread调用。 Check your argc to make sure you got the number of command line arguments expected as well.检查您的argc以确保您也获得了预期的命令行 arguments 的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM