How to get the SHA-1/MD5 checksum of a file with Qt?(如何使用 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 校验和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Qt 获取文件的 SHA-1/MD5 校验和?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
