1

am learning to do the hash of a file in C using OpenSSL but I always get the same hash. I have tried different files and content but the hash do not change. If i use different files it should show different hash.I am not sure where the problem is.

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
  • 2
    In the code you posted, you are not checking the return values of the function calls `open` and `read` for failure. Did you ever check whether these functions are failing? – Andreas Wenzel Jul 13 '20 at 18:53

1 Answers1

4

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. 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. Check your argc to make sure you got the number of command line arguments expected as well.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174