如何使用Qt获取文件的SHA-1/MD5校验和? [英] How to get the SHA-1/MD5 checksum of a file with Qt?

查看:525
本文介绍了如何使用Qt获取文件的SHA-1/MD5校验和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Qt中获取磁盘上文件的MD5或SHA-1校验和/哈希?

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.

推荐答案

使用QFile打开文件,然后调用readAll()将其内容拉入QByteArray.然后将其用于QCryptographicHash::hash(const QByteArray& data, Algorithm method)调用.

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.

在Qt5中,您可以使用addData():

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

这篇关于如何使用Qt获取文件的SHA-1/MD5校验和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆