PDA

View Full Version : QCryptographicHash an entire file



pyramation
3rd November 2010, 18:58
Hello all!

I am successfully hashing an entire file, however, my method seems to produce different results for different block sizes. Let me explain...

My fear is that I don't want to use a Qt data structure to store an entire file to memory, since I want to hash arbitrarily large files. Hence, I am chunking the file into pieces of 'blocksize', and then using addData() to add the data to the hash.

The problem is that for different values of 'blocksize', I am getting a different hash. Any ideas?



FILE * fd = fopen(fileName.toAscii().data(), "rb");
if (!fd) return;


fseek(fd, 0, SEEK_END);
long fSize = ftell(fd);
fseek(fd, 0, SEEK_SET);

QCryptographicHash krypo(QCryptographicHash::Sha1);
const long blockSize = 8192;
char block[blockSize];
memset(block, 0, blockSize);
fread(block, 1, blockSize, fd);
long c = fSize;
while( c > 0) {

krypo.addData(block, (c < blockSize) ? c : blockSize);
c-=(c < blockSize) ? c : blockSize;
}
QByteArray hash = krypo.result();


I just noticed a bug. I guess it takes posting it to find. I'm not fread'ing in the while loop. I'll fix the bug and see if it works, and post the result.

Added after 14 minutes:

Ok, this code works if anyone is interested. Also, please let me know if I should not be using fread, fseek, etc. I hope those work on windows (I use Linux and OS X).


fseek(fd, 0, SEEK_END);
hashee.fSize = ftell(fd);
fseek(fd, 0, SEEK_SET);

QCryptographicHash krypo(QCryptographicHash::Sha1);
const long blockSize = 8192;
char block[blockSize];
long c = hashee.fSize;
while( c > 0) {
fread(block, 1, (c < blockSize) ? c : blockSize, fd);
krypo.addData(block, (c < blockSize) ? c : blockSize);
c-=(c < blockSize) ? c : blockSize;
}
QByteArray hash = krypo.result();

wysota
3rd November 2010, 19:09
Why do you complicate things?

QCryptographicHash crypto(QCryptographicHash::Sha1);
QFile file(fileName);
file.open(QFile::ReadOnly);
while(!file.atEnd()){
crypto.addData(file.read(8192));
}
QByteArray hash = crypto.result();

pyramation
3rd November 2010, 23:41
@wysota :

Thanks for the tip!