I want to get hash of a binary file whose name I have. I have tried the following, but then realized that SHA1()
is returning hash value for the string ( name of the file). But I want to run it on the file itself. Any pointers on how to do that would be great.
char *fileName = "/bin/ls"
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1((unsigned char *)fileName, strlen(fileName),hash);
You need to read the file chunk by chunk, and compute the digest chunk by chunk.
Read chunks up to e.g. 2048 bytes with
fread
. UseSHA1_Init
in the beginning,SHA1_Update
for each chunk, andSHA1_Final
in the end.You can use plain
SHA1
function if you read the entire file in one gulp, but this is not recommended.Another method is to memory-map the file (see
mmap()
or whatever the Windows equivalent is) and use plainSHA1
. This method is very efficient but less portable than the other one.You need just give argument of file context to SHA1(). The variable fileName contains string "/bin/ls" and SHA1() function returns hash of that string. Here is simple example how to read file and get hash
I hope buffer size of string (2048) will be enough for the file context.
Thanks to everyone's comments I solved the problem. I am posting the code here, so others might find it beneficial.
I don't know how your SHA1() function works (is it from libssl?), but I assume that by
SHA1((unsigned char *)fileName, strlen(fileName),hash);
you are hashing file name, so
/bin/ls
string. You need to read file content byte by byte into a buffer and hash it.