Qt读取MD5

1、读取MD5值

QByteArray MainWindow::getFileMd5(QString filePath)
{
    QFile localFile(filePath);

    if (!localFile.open(QFile::ReadOnly))
    {
        qDebug() << "file open error.";
        return 0;
    } 

    /*QCryptographicHash类提供了一种生成加密哈希的方法。
    QCryptographicHash可用于生成二进制或文本数据的密码散列。
    目前支持MD4、MD5和SHA-1。 
    */ 

    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;
}

2、获取MD5值
调用上述函数,传入文件路径

   QString filePath = "/home/test";
   QString md5 = getFileMd5(filePath).toHex().toUpper();

转自:https://blog.csdn.net/qq_40194498/article/details/82391498
(一些博客中只有怎么生成md5值,返回的是一个QByteArray,但是并没有告诉怎么获取正确格式的md5,这篇博客指出了。)

3、验证代码生成的MD5值
为了验证用代码获取的MD5值是否正确,可以用windows自带的命令进行查看:

D:\>certutil -hashfile md5test.txt MD5
MD5 哈希(文件 md5test.txt):
d6 f6 bb 38 b5 6b 67 8f 34 9b e4 d6 2f 52 73 1f
CertUtil: -hashfile 命令成功完成。

D:\>certutil -hashfile md5test.txt SHA1
SHA1 哈希(文件 md5test.txt):
fc 58 8e 1f 62 8e fb 19 1d 74 c8 c2 06 6a 12 93 f9 57 bd cd
CertUtil: -hashfile 命令成功完成。

D:\>certutil -hashfile md5test.txt SHA256
SHA256 哈希(文件 md5test.txt):
c5 5a 3d 2b 3e a7 6c f3 7e 93 bd ca 1b 43 8b 22 49 a5 9a c6 33 76 07 e0 35 cc f8 a4 c4 5c 16 90
CertUtil: -hashfile 命令成功完成。

转自:https://www.cnblogs.com/fuyuanming/p/5968763.html
注意命令中MD5是大写,发现生成的MD5值是小写字母加数字,只需要把调用代码改成:

getFileMd5(filePath).toHex().toLower();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值