这篇文章上次修改于 297 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
计算字符串 md5 值
QCryptographicHash
,提供一种生成加密散列的方法,Hash
叫作散列表,也叫作哈希。- 当前支持
MD4, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512
等算法 使用方式:
QString str = "hello world!"; //返回哈希数据,第二个参数是采用何种算法 QByteArray hashData = QCryptographicHash::hash(str .toLocal8Bit(),QCryptographicHash::Md5); //返回字节数组的十六进制编码,编码使用数字0-9和字母a-f str = hashData.toHex();
计算文件 md5
static const QString fileMd5(const QString &path)
{
QFile sourceFile(path);
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(QCryptographicHash::Md5);
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();
}
没有评论