QT 获取MD5值

QT提供了QCryptographicHash类,很方便的实现获取md5/md4/sha1码

字符串转MD5

一、实例化QCryptographicHash,然后addData(), 最后获取result();

[cpp]  view plain  copy
  1. QString pwd="123456";  
  2. QString md5;  
  3. QByteArray ba,bb;  
  4. QCryptographicHash md(QCryptographicHash::Md5);  
  5. ba.append(pwd);  
  6. md.addData(ba);  
  7. bb = md.result();  
  8. md5.append(bb.toHex());   

二、通过静态Hash()方法直接获取

[cpp]  view plain  copy
  1. QString md5;  
  2. QString pwd="123456";  
  3. QByteArray bb;  
  4. bb = QCryptographicHash::hash ( pwd.toAscii(), QCryptographicHash::Md5 );  
  5. md5.append(bb.toHex());  

-------------------------------------------------------------------------------------------------------------------------

获取文件的MD5码:

小文件内容加密的时候,直接将文件内容传进入加密即可,但遇到大文件的时候这样的办法需要优化。

思路就是:在循环中不停读文件,读到一定大小的文件内容,就拿去算MD5值,这样就保证了保存文件内容的变量不会溢出。

[cpp]  view plain  copy
  1. /* 方法1 */  
  2.     QFile theFile(fileNamePath);  
  3.     theFile.open(QIODevice::ReadOnly);  
  4.     QByteArray ba = QCryptographicHash::hash(theFile.readAll(), QCryptographicHash::Md5);  
  5.     theFile.close();  
  6.     qDebug() << ba.toHex().constData();  
[cpp]  view plain  copy
  1. /* 方法2 */  
  2. /* 
  3. *   获取文件md5值 
  4. */  
  5. QByteArray MainWindow::getFileMd5(QString filePath)  
  6. {  
  7.     QFile localFile(filePath);  
  8.   
  9.     if (!localFile.open(QFile::ReadOnly))  
  10.     {  
  11.         qDebug() << "file open error.";  
  12.         return 0;  
  13.     }  
  14.   
  15.     QCryptographicHash ch(QCryptographicHash::Md5);  
  16.   
  17.     quint64 totalBytes = 0;  
  18.     quint64 bytesWritten = 0;  
  19.     quint64 bytesToWrite = 0;  
  20.     quint64 loadSize = 1024 * 4;  
  21.     QByteArray buf;  
  22.   
  23.     totalBytes = localFile.size();  
  24.     bytesToWrite = totalBytes;  
  25.   
  26.     while (1)  
  27.     {  
  28.         if(bytesToWrite > 0)  
  29.         {  
  30.             buf = localFile.read(qMin(bytesToWrite, loadSize));  
  31.             ch.addData(buf);  
  32.             bytesWritten += buf.length();  
  33.             bytesToWrite -= buf.length();  
  34.             buf.resize(0);  
  35.         }  
  36.         else  
  37.         {  
  38.             break;  
  39.         }  
  40.   
  41.         if(bytesWritten == totalBytes)  
  42.         {  
  43.             break;  
  44.         }  
  45.     }  
  46.   
  47.     localFile.close();  
  48.     QByteArray md5 = ch.result();  
  49.   
  50.     return md5;  
  51. }  


最后解释一下QByteArray的 toHex()方法:

Qt中QByteArray存储的十六进制数,比如是0x9f,实际是以ascll码存储的,存储形式为'\x9f','\x9f' 执行toHex() 的结果为 “9f”的字符串。

另外如果需要比较的话,需要用array.at(0) == '\x9f'表示,而不是array.at(0) == 0x9f;


<think>我们参考了用户提供的三个引用,其中引用[2]和引用[3]都是关于Qt获取文件MD5的。 引用[2]展示了一个使用Qt一次性读取整个文件并计算MD5的示例代码,但这种方法不适用于大文件,因为会占用大量内存。 引用[3]提到QtQCryptographicHash类可以用于计算MD5,并且支持多种算法,但没有提供具体代码。 用户的问题:使用Qt获取文件md5的方法 考虑到用户可能处理大文件,我们需要提供一种逐块读取文件的方法,以避免内存不足。 因此,我们可以提供两种方法: 1. 对于小文件,可以一次性读取并计算MD5(如引用[2]所示)。 2. 对于大文件,应该分块读取,逐步更新MD5。 由于引用[3]特别指出了大文件的情况,我们将重点提供大文件的处理方式。 步骤: 1. 使用QFile打开文件。 2. 创建QCryptographicHash对象,指定算法为MD5。 3. 循环读取文件块,并更新到hash对象中。 4. 完成读取后,获取最终的hash并转换为十六进制字符串。 注意:我们需要处理文件打开失败的情况。 下面提供两种方法的代码示例: </think>### Qt获取文件MD5的方法 在Qt获取文件MD5主要有两种方法,根据文件大小选择不同方案: #### 1. **小文件处理方案**(一次性读取) 适用于小于100MB的文件,直接读取整个文件内容计算MD5: ```cpp #include <QCryptographicHash> #include <QFile> QString getFileMd5(const QString &filePath) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { return QString(); // 返回空字符串表示失败 } // 一次性读取全部内容并计算MD5 QByteArray hash = QCryptographicHash::hash(file.readAll(), QCryptographicHash::Md5); file.close(); return hash.toHex(); // 返回16进制字符串 } ``` **特点**: - 代码简洁高效(基于引用[2]实现[^2]) - 内存占用等于文件大小 - 不适用于大文件 #### 2. **大文件处理方案**(分块读取) 适用于GB级大文件,分块读取节省内存: ```cpp QString getLargeFileMd5(const QString &filePath) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { return QString(); } constexpr qint64 bufferSize = 1024 * 1024; // 1MB缓冲区 QByteArray buffer(bufferSize, Qt::Uninitialized); QCryptographicHash hash(QCryptographicHash::Md5); while (!file.atEnd()) { qint64 bytesRead = file.read(buffer.data(), bufferSize); hash.addData(buffer.constData(), bytesRead); } file.close(); return hash.result().toHex(); // 返回16进制字符串 } ``` **特点**: - 恒定内存占用(约1MB) - 支持超大文件处理(基于引用[3]原理[^3]) - 计算时间随文件大小线性增加 #### 使用示例 ```cpp int main() { QString md5_small = getFileMd5("test.jpg"); QString md5_large = getLargeFileMd5("large_video.mp4"); qDebug() << "Small file MD5:" << md5_small; qDebug() << "Large file MD5:" << md5_large; } ``` #### 注意事项 1. **文件路径**:确保传入正确路径(绝对路径或工作目录相对路径) 2. **错误处理**:检查返回是否为空字符串判断操作是否成功 3. **算法选择**:将`QCryptographicHash::Md5`替换为`QCryptographicHash::Sha256`可计算SHA-256 4. **性能优化**:机械硬盘建议缓冲区设为1MB,SSD可增大缓冲区到10MB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值