【发布时间】: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
【问题讨论】:
-
在您发布的代码中,您没有检查函数调用
open和read的返回值是否失败。你有没有检查过这些功能是否失败了?
标签: c file hash openssl cryptography