QT提供了QCryptographicHash类,很方便的实现获取md5/md4/sha1码
字符串转MD5:
一、实例化QCryptographicHash,然后addData(), 最后获取result();
- QString pwd="123456";
- QString md5;
- QByteArray ba,bb;
- QCryptographicHash md(QCryptographicHash::Md5);
- ba.append(pwd);
- md.addData(ba);
- bb = md.result();
- md5.append(bb.toHex());
二、通过静态Hash()方法直接获取:
- QString md5;
- QString pwd="123456";
- QByteArray bb;
- bb = QCryptographicHash::hash ( pwd.toAscii(), QCryptographicHash::Md5 );
- md5.append(bb.toHex());
-------------------------------------------------------------------------------------------------------------------------
获取文件的MD5码:
小文件内容加密的时候,直接将文件内容传进入加密即可,但遇到大文件的时候这样的办法需要优化。
思路就是:在循环中不停读文件,读到一定大小的文件内容,就拿去算MD5值,这样就保证了保存文件内容的变量不会溢出。
- /* 方法1 */
- QFile theFile(fileNamePath);
- theFile.open(QIODevice::ReadOnly);
- QByteArray ba = QCryptographicHash::hash(theFile.readAll(), QCryptographicHash::Md5);
- theFile.close();
- qDebug() << ba.toHex().constData();
- /* 方法2 */
- /*
- * 获取文件md5值
- */
- QByteArray MainWindow::getFileMd5(QString filePath)
- {
- QFile localFile(filePath);
- if (!localFile.open(QFile::ReadOnly))
- {
- qDebug() << "file open error.";
- return 0;
- }
- QCryptographicHash ch(QCryptographicHash::Md5);
- quint64 totalBytes = 0;
- quint64 bytesWritten = 0;
- quint64 bytesToWrite = 0;
- quint64 loadSize = 1024 * 4;
- QByteArray buf;
- totalBytes = localFile.size();
- bytesToWrite = totalBytes;
- while (1)
- {
- if(bytesToWrite > 0)
- {
- buf = localFile.read(qMin(bytesToWrite, loadSize));
- ch.addData(buf);
- bytesWritten += buf.length();
- bytesToWrite -= buf.length();
- buf.resize(0);
- }
- else
- {
- break;
- }
- if(bytesWritten == totalBytes)
- {
- break;
- }
- }
- localFile.close();
- QByteArray md5 = ch.result();
- return md5;
- }
最后解释一下QByteArray的 toHex()方法:
Qt中QByteArray存储的十六进制数,比如是0x9f,实际是以ascll码存储的,存储形式为'\x9f','\x9f' 执行toHex() 的结果为 “9f”的字符串。
另外如果需要比较的话,需要用array.at(0) == '\x9f'表示,而不是array.at(0) == 0x9f;