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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值