29

Is there a way to get the MD5 or SHA-1 checksum/hash of a file on disk in Qt?

For example, I have the file path and I might need to verify that the contents of that file matches a certain hash value.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
user2282405
  • 873
  • 2
  • 9
  • 10
  • See also [my answer to a more generic question](https://stackoverflow.com/a/28784281/427158) that uses Qt for computing the SHA1 hash of a file. – maxschlepzig Dec 21 '21 at 12:17

2 Answers2

54

Open the file with QFile, and call readAll() to pull it's contents into a QByteArray. Then use that for the QCryptographicHash::hash(const QByteArray& data, Algorithm method) call.

In Qt5 you can use addData():

// Returns empty QByteArray() on failure.
QByteArray fileChecksum(const QString &fileName, 
                        QCryptographicHash::Algorithm hashAlgorithm)
{
    QFile f(fileName);
    if (f.open(QFile::ReadOnly)) {
        QCryptographicHash hash(hashAlgorithm);
        if (hash.addData(&f)) {
            return hash.result();
        }
    }
    return QByteArray();
}
sashoalm
  • 75,001
  • 122
  • 434
  • 781
cmannett85
  • 21,725
  • 8
  • 76
  • 119
  • 18
    readAll() reads everything into memory at once, not a good idea for large files. I'd rather use addData(&file). – Frank Osterfeld May 05 '13 at 10:45
  • 2
    @FrankOsterfeld I agree, I was simplifying to get the point across - it's the OP's responsibility to make sure it doesn't crash the system. – cmannett85 May 05 '13 at 10:50
  • In Qt 4.8 you can also use addData() http://doc.qt.io/qt-4.8/qcryptographichash.html#addData – tropikan4 Jun 23 '15 at 12:49
  • @tropikan4 but does doesn't take in a QIODevice, you have to read all the contents of the file in Qt 4.8, and pass that in. – phyatt Aug 17 '17 at 15:53
4

If you are using Qt4, you can try this.

QByteArray fileChecksum(const QString &fileName, QCryptographicHash::Algorithm hashAlgorithm)
{
    QFile sourceFile(fileName);
    qint64 fileSize = sourceFile.size();
    const qint64 bufferSize = 10240;

    if (sourceFile.open(QIODevice::ReadOnly))
    {
        char buffer[bufferSize];
        int bytesRead;
        int readSize = qMin(fileSize, bufferSize);

        QCryptographicHash hash(hashAlgorithm);
        while (readSize > 0 && (bytesRead = sourceFile.read(buffer, readSize)) > 0) 
        {
            fileSize -= bytesRead;
            hash.addData(buffer, bytesRead);
            readSize = qMin(fileSize, bufferSize);
        }

        sourceFile.close();
        return QString(hash.result().toHex());
    }
    return QString();
}

Because

bool QCryptographicHash::addData(QIODevice *device)

Reads the data from the open QIODevice device until it ends and hashes it. Returns true if reading was successful.

This function was introduced in Qt 5.0.

References: https://www.qtcentre.org/threads/47635-Calculate-MD5-sum-of-a-big-file

Destiny
  • 466
  • 5
  • 8