QT的MD5计算

简介

基于QT进行MD5值计算,安装版本为QT5.13.0,需要#include "QCryptographicHash"

接口介绍

QCryptographicHash类中Algorithm枚举了可以计算的类型。计算方式分为两种:通过addData接口动态计算,通过hash接口静态计算;图中截取了该类的公共接口

使用方法

  1. 动态计算
    先创建一个实例并指定计算的类型,调用reset接口复位对象,通过addData接口往对象中填入数据,最终通过resault接口获取计算结果
    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.reset();

    hash.addData(ui->source->toPlainText().toLocal8Bit());

    ui->resault->setText(hash.result().toHex().data());
  1. 静态计算
    直接将数据放到QCryptographicHash的hash接口内作为参数,同时指定计算方式,从返回值即可得到计算的结果
    QByteArray value;

    value = QCryptographicHash::hash(ui->source->toPlainText().toLocal8Bit(),QCryptographicHash::Md5);

    ui->resault->setText(value.toHex().data());

文件校验

使用动态计算的方式,从文件中按段读取文本内容,使用addData接口逐渐进行计算

    /* 打开文件 */
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"文件打开错误";
        return;
    }

    QCryptographicHash md5_hash(QCryptographicHash::Md5);
    md5_hash.reset();

    /* 文本读取 */
    while(!file.atEnd())
    {
        md5_hash.addData(file.readLine());
    }

    ui->md5output->setPlainText(md5_hash.result().toHex());
原文地址:https://www.cnblogs.com/niu-li/p/12612455.html