QT 自带有QCryptographicHash类可以进行很方便的进行 md4 、md5等加密。使用方法很简单,直接提供了一个静态的方法。
QByteArray QCryptographicHash::hash(const QByteArray &data, Algorithm method)
data就是要加密的数据, method是加密的方法,看官方文档选择加密的方式就行。
QString strCipher = QCryptographicHash::hash(strKey.toLocal8Bit(), QCryptographicHash::Md5);
QString MainWindow::fileMd5(const QString &sourceFilePath) {
QFile sourceFile(sourceFilePath);
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();
}