How to get the SHA-1/MD5 checksum of a file with Qt?

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


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();
}