Qt 使用MD5给数据加密方法

重点:

1.通常在存储密码的时候需要对数据进行加密,通常采用Md5进行加密。

cpp 复制代码
//存储密码时候
//读取存储的用户名和密码, 密码是经过加密的
void TDialogLogin::readSettings()
{
    QSettings settings;     //创建QSettings对象
    bool saved=settings.value("saved",false).toBool();      //读取 saved键的值
    m_user=settings.value("Username", "user").toString();   //读取 Username 键的值,默   认为"user"

    QString defaultPSWD=encrypt("12345");       //默认密码"12345"加密后的数据

    m_pswd=settings.value("PSWD",defaultPSWD).toString();   //读取PSWD 键的值

    if (saved)
        ui->editUser->setText(m_user);

    ui->chkBoxSave->setChecked(saved);
}

//保存用户名,密码等设置
void TDialogLogin::writeSettings()
{
    QSettings   settings;   //注册表键组
    settings.setValue("Username",m_user);       //用户名
    settings.setValue("PSWD",m_pswd);           //密码,经过加密的
    settings.setValue("saved",ui->chkBoxSave->isChecked());
}

QString TDialogLogin::encrypt(const QString &str)
{ //字符串MD5算法加密
    QByteArray btArray= str.toLocal8Bit();  //字符串转换为字节数组数据

    QCryptographicHash hash(QCryptographicHash::Md5);  //Md5加密算法
    hash.addData(btArray);  //添加数据到加密哈希值

    QByteArray resultArray =hash.result();  //返回最终的哈希值
    QString md5 =resultArray.toHex();       //转换为16进制字符串
    return  md5;
}

//判断用户输入账号和密码
//"确定"按钮响应
void TDialogLogin::on_btnOK_clicked()
{
    QString user=ui->editUser->text().trimmed();    //输入的用户名
    QString pswd=ui->editPSWD->text().trimmed();    //输入的密码
    QString encrptPSWD=encrypt(pswd);   //对输入的密码进行加密

    if ((user==m_user)&&(encrptPSWD==m_pswd))       //如果用户名和密码正确
    {
        writeSettings();    //保存设置
        this->accept();     //accept(),关闭对话框
    }
    else
    {
        m_tryCount++;       //错误次数
        if (m_tryCount>3)
        {
            QMessageBox::critical(this, "错误", "输入错误次数太多,强行退出");
            this->reject(); //reject(), 关闭对话框
        }
        else
            QMessageBox::warning(this, "错误提示", "用户名或密码错误");
    }
}
相关推荐
Felix_One1 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237179 天前
C语言-数组练习进阶
c语言·开发语言·算法