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

user2282405 picture user2282405 · May 5, 2013 · Viewed 20.1k times · Source

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.

Answer

cmannett85 picture cmannett85 · May 5, 2013

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