簡體   English   中英

一個文件的OpenSSL hash在C中是一樣的

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

我正在學習使用 OpenSSL 執行 C 中的文件的 hash 但我總是得到相同的 Z0800FCZ28294C359E45B 我嘗試了不同的文件和內容,但 hash 沒有改變。 如果我使用不同的文件,它應該顯示不同的 hash。我不確定問題出在哪里。

這是我的代碼:

#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

我認為你的問題就在這里:

i = read(fd, buff, i);

i初始化為零,因此您告訴read()最多讀取 0 個字符。 相反,您應該指定緩沖區大小:

i = read(fd, buff, BUFF_SIZE);

正如 Andreas Wenzel 的評論所建議的那樣,我還建議您添加錯誤檢查來openread調用。 檢查您的argc以確保您也獲得了預期的命令行 arguments 的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM