在Qt中有没有一种方法可以获取磁盘上文件的MD5或SHA-1的校验和/哈希值?
例如,我有文件路径,可能需要验证该文件的内容是否与某个哈希值匹配。
使用QFile
打开文件,然后调用readAll()
将其内容读入QByteArray
中。然后将其用于QCryptographicHash::hash(const QByteArray& data, Algorithm method)
的调用。
在Qt5中,您可以使用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();
}
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();
}
因为:
bool QCryptographicHash::addData(QIODevice *device)
从打开的QIODevice设备中读取数据,直到读取完毕并进行哈希处理。如果读取成功,则返回true。
该函数在Qt 5.0中引入。
参考资料:https://www.qtcentre.org/threads/47635-Calculate-MD5-sum-of-a-big-file