I'd like to hash a file in the same way that git hash-object
does, so I can compare it to an existing hash, but using Qt and C++.
The answers to this question show how to get the same hash, but none of the examples use C++.
So far this is what we've tried:
QString fileName = entry.toObject().value( "name" ).toString();
QByteArray shaJson = entry.toObject().value( "sha" ).toString().toUtf8();
QByteArray shaFile;
QFile f( QString( "%1/%2" ).arg( QCoreApplication::applicationDirPath() ).arg( fileName ) );
if( f.open(QFile::ReadOnly ) )
{
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData( QString( "blob " ).toUtf8() ); // start with the string "blob "
hash.addData( QString( "%1" ).arg( f.size() ).toUtf8() ); // add size in bytes of the content
hash.addData( QString( "\0" ).toUtf8() ); // null byte
hash.addData( f.readAll() ); // actual file content
shaFile = hash.result().toHex();
if( shaFile != shaJson ){
}
}
How to implement this hashing method with Qt?
Edit:
Here's an example hash output:
ccbf4f0a52fd5ac59e18448ebadf2ef37c62f54f
Computed with git hash-object
from this file:
https://raw.githubusercontent.com/ilia3101/MLV-App/master/pixel_maps/80000301_1808x1007.fpm
So that's the hash we also like to compute with Qt.
QString::toUtf8
include a terminating null character? If so, it will change the hash results, as the input will be different.QCryptographicHash
works. So it's not a question of how to do sha1 hash. The hard part is combining all the parts in the same way git does when hashing... I've added an example file and the desired hash for it.