网站开发有哪些风险,淘宝新闻最新消息,今天刚刚发生的新闻最新新闻,百度统计数据分析目录
0.环境
1.背景
2.详细代码
2.1 .h主要代码
2.2 .cpp主要代码#xff0c;主要实现上述的四个方法 0.环境 windows 11 64位 Qt Creator 4.13.1 1.背景 项目需求#xff1a;我们项目中有配置文件#xff08;类似.txt#xff0c;但不是这个格式#xff0c;本文以…目录
0.环境
1.背景
2.详细代码
2.1 .h主要代码
2.2 .cpp主要代码主要实现上述的四个方法 0.环境 windows 11 64位 Qt Creator 4.13.1 1.背景 项目需求我们项目中有配置文件类似.txt但不是这个格式本文以.txt举例这个配置文件希望对用户不可见但是希望对工程师可见。所以需要开发一个类似将明文变为密文的方法在开发时将.txt变为明文在提供给客户时将.txt变为密文。 本文主要使用toBase64的方式将.txt的内容进行编码需要注意的是toBase64方法这实际上并不是一个加密方法它只是一种编码方式可以很容易地被解码。但我们的项目要求不高只需看不出来是什么内容即可所以选择了这种方式。如果您的项目有加密文件的需求建议考虑真正的加密方法例如AES。 我的测试界面包含两个按钮加密和解密 点击两个按钮都会弹出QFileDialog选择框选择你想要加密/解密的文件 原test.txt内容 点击加密按钮会调用加密方法将test.txt中的明文内容变为编码非明文 点击解密按钮会调用解密方法将test.txt中的编码恢复为明文 2.详细代码 界面我是通过.ui文件拖控件上去的这里就不做展示加密控件名为【btn_encrypt】解密控件名为【btn_decrypt】 2.1 .h主要代码
两个按钮的槽对应界面的加密和解密按钮
private slots:void on_btn_encrypt_clicked();void on_btn_decrypt_clicked();
两个方法主要对应加密、解密
private:QString encrypt(const QString plainText);//加密函数QString decrypt(const QString encryptedText);//解密函数 2.2 .cpp主要代码主要实现上述的四个方法
void MainWindow::on_btn_encrypt_clicked()
{//打开一个文件对话框并获取选择的文件路径QString filePath ;filePath QFileDialog::getOpenFileName();qDebug()要加密的文件路径为 filePath;QString encryptText;QFile inputFile(filePath);if (inputFile.open(QIODevice::ReadOnly| QIODevice::Text)){QTextStream in(inputFile);QString dataText in.readAll();inputFile.close();qDebug()-----data:\ndataText;encryptText encrypt(dataText);qDebug()-----encryptText:\nencryptText;}QFile outputFile(filePath);if (outputFile.open(QIODevice::WriteOnly)) {QTextStream out(outputFile);out encryptText;outputFile.close();qDebug() encrypt completed.;} else {qDebug() Failed to open output file.;}
}
void MainWindow::on_btn_decrypt_clicked()
{//打开一个文件对话框并获取选择的文件路径QString filePath ;filePath QFileDialog::getOpenFileName();qDebug()要解密的文件路径为 filePath;QFile inputFile(filePath);if (inputFile.open(QIODevice::ReadOnly| QIODevice::Text)) {QTextStream in(inputFile);QString encryptedText in.readAll();inputFile.close();qDebug()-----encryptedText:\nencryptedText;QString decryptedText decrypt(encryptedText);QFile outputFile(filePath);if (outputFile.open(QIODevice::WriteOnly)) {QTextStream out(outputFile);out decryptedText;outputFile.close();qDebug() Decryption completed.;qDebug() -----decryptedText:\ndecryptedText;} else {qDebug() Failed to open output file.;}} else {qDebug() Failed to open input file.;}
}
QString MainWindow::encrypt(const QString plainText)
{QByteArray byteArray plainText.toUtf8();QByteArray encryptedData byteArray.toBase64();return QString(encryptedData);
}
QString MainWindow::decrypt(const QString encryptedText)
{QByteArray encryptedData encryptedText.toUtf8();QByteArray decryptedData QByteArray::fromBase64(encryptedData);return QString(decryptedData);
}
至此可以实现开头的截图效果项目记录特此分享
本文的项目我已放入github中以下链接可访问
Wynne-nuo/encrypt_TXT_file_by_base64 (github.com) 参考Qt以Base64加密作为基础实现3种加解密方式包含中文处理-CSDN博客 --END--