Qt使用AES128加密一段文字实例

本实例使用了现成的Qt库:https://github.com/bricke/Qt-AES

主要代码:

#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "qaesencryption.h"
#include <QCryptographicHash>

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::on_buttonEncode_clicked()
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey = QCryptographicHash::hash(ui->textKey->toPlainText().toUtf8(), QCryptographicHash::Md5);
    QByteArray encodedText = encryption.encode(ui->textOrigin->toPlainText().toUtf8(), hashKey);
    ui->textEncode->setText(QString::fromLatin1(encodedText.toBase64()));
}

void MainWidget::on_buttonDecode_clicked()
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::ECB, QAESEncryption::ZERO);
    QByteArray hashKey = QCryptographicHash::hash(ui->textKey->toPlainText().toUtf8(), QCryptographicHash::Md5);
    QByteArray decodedText = encryption.decode(QByteArray::fromBase64(ui->textEncode->toPlainText().toLatin1()), hashKey);
    ui->textDecode->setText(QString::fromUtf8(decodedText));
}

运行效果:

(---------完--------)

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Qt是一种流行的跨平台应用程序开发框架,提供了各种功能丰富的类库和工具,包括AES加密和解密算法的支持。 AES(Advanced Encryption Standard)是一种对称加密算法,被广泛应用于保护数据的机密性和安全性。在Qt中,我们可以使用QCryptographic类库来实现AES加密和解密操作。 首先,我们需要在项目中包含QCryptographic库的头文件: #include <QCryptographicHash> 然后,使用该库中的相关方法来进行加密和解密操作。例如,使用AES-128加密算法: QString plaintext = "Hello, World!"; QString password = "SecretPassword"; // 将明文转换为字节数组 QByteArray plaintextBytes = plaintext.toUtf8(); // 创建AES加密对象 QAESEncryption aesEncrypt(QAESEncryption::AES_128, QAESEncryption::CBC); // 设置加密密码 aesEncrypt.setKey(password.toUtf8()); // 加密明文数据 QByteArray encryptedData = aesEncrypt.encode(plaintextBytes); // 将加密数据转换为十六进制字符串 QString encryptedText = encryptedData.toHex(); // 输出加密后的结果 qDebug() << "Encrypted text: " << encryptedText; 上述代码将明文字符串"Hello, World!"使用AES-128算法加密加密密码为"SecretPassword",然后将加密后的数据转换为十六进制字符串并输出。 解密操作可以使用相同的加密密码和加密算法: // 将加密后的字符串转换为字节数组 QByteArray encryptedData = QByteArray::fromHex(encryptedText.toUtf8()); // 创建AES解密对象 QAESEncryption aesDecrypt(QAESEncryption::AES_128, QAESEncryption::CBC); // 设置解密密码 aesDecrypt.setKey(password.toUtf8()); // 解密数据 QByteArray decryptedData = aesDecrypt.decode(encryptedData); // 将解密后的字节数组转换为明文字符串 QString decryptedText = QString::fromUtf8(decryptedData); // 输出解密结果 qDebug() << "Decrypted text: " << decryptedText; 上述代码将加密后的十六进制字符串转换为字节数组,然后使用AES-128算法和密码"SecretPassword"进行解密操作,最后将解密后的字节数组转换为明文字符串并输出。 通过以上代码片段,我们可以在Qt使用AES算法进行加密和解密操作,保护我们的数据的机密性和安全性。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值