一、计算字符串md5值
(1)QCryptographicHash,提供一种生成加密散列的方法,Hash叫作散列表,也叫作哈希。
(2)当前支持MD4, MD5, SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512等算法
QString str = "hello world!";
//返回哈希数据,第二个参数是采用何种算法
QByteArray hashData = QCryptographicHash::hash(str .toLocal8Bit(),QCryptographicHash::Md5);
//返回字节数组的十六进制编码,编码使用数字0-9和字母a-f
str = hashData.toHex();
二、计算文件md5值
const QString FileOperater::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();
}