user1535814
user1535814

Reputation: 66

Computing hash of file with OpenSSL gives different results depending on chunk size

I want to generate a hash of a file with openssl.

CFile file;
CFileException fileException;
file.open(filename, CFile::modeRead, &fileException);
file.SeekToBegin();
unsigned char buffer[1024];
SHA_CTX context;
SHA1_Init(&context);
while(unsigned int bytesRead = file.Read(buffer, sizeof(buffer)) > 0)
{
    SHA1_Update(&context, buffer, bytesRead);
}
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1_Final(hash, &context);

It seems to work, but if I change the chunk size, I get different results in hash. What's going wrong here?

Greets

Upvotes: 1

Views: 283

Answers (1)

Jumbogram
Jumbogram

Reputation: 2259

Here's the problem:

while(unsigned int bytesRead = file.Read(buffer, sizeof(buffer)) > 0)

This works as:

bytesRead = ( file.Read(buffer, sizeof(buffer)) > 0 )

and not

(bytesRead = file.Read(buffer, sizeof(buffer))) > 0.

Comparision is higher priority than assigment. Adding another set of paranthesis will solve your problem. See http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages

Upvotes: 2

Related Questions