【问题标题】:HowTo Crypt/Encrypt some string (e.g. Password) on Qt simple如何在 Qt simple 上解密/加密一些字符串(例如密码)
【发布时间】:2023-12-05 18:11:01
【问题描述】:

这是我得到的:

  • Qt SDK 版本 4.6.2
  • Windows XP

问题:如何简单地加密和加密简单的 QString 值?我需要这个能够将一些加密字符串保存到 INI 文件中,并在重新打开应用程序后将字符串加密为正常的密码字符串值。

PS:我正在寻找简单而好的解决方案。

感谢您的帮助!

【问题讨论】:

  • 为了验证密码,您不需要再次解密它,因此存储强(加盐)哈希是比存储密码本身更好的策略。

标签: qt encryption qt4


【解决方案1】:

这里有 SimpleCrypt:https://wiki.qt.io/Simple_encryption_with_SimpleCrypt,顾名思义,作者说该类不提供强加密,但在我看来它非常好。

您可以在此处下载一个工作示例:http://www.qtcentre.org/threads/45346-Encrypting-an-existing-sqlite-database-in-sqlcipher?p=206406#post206406

#include <QtGui>
#include "simplecrypt.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString FreeTrialStartDate ;

    //Set The Encryption And Decryption Key
    SimpleCrypt processSimpleCrypt(89473829);

    QString FreeTrialStartsOn("22/11/2011");

    //Encrypt
    FreeTrialStartDate = processSimpleCrypt.encryptToString(FreeTrialStartsOn);

    qDebug() << "Encrypted 22/11/2011 to" << FreeTrialStartDate;

    //Decrypt
    QString decrypt = processSimpleCrypt.decryptToString(FreeTrialStartDate);

    qDebug() << "Decrypted 22/11/2011 to" << decrypt;

    return a.exec();
}

【讨论】:

    【解决方案2】:

    如果您只想将其用作密码,请使用QCryptographicHash。散列密码,将其保存到文件中。然后,当您要比较时,对输入进行哈希处理并将其与保存的密码进行比较。当然这不是很安全,您可以进入salting 之类的内容以提高安全性。

    如果您只想加密和解密存储在文件中的字符串,请使用cipher。看看BotanCrypto++

    这当然取决于您想要的安全级别。

    【讨论】:

      【解决方案3】:

      将数据添加到加密哈希中:

      QByteArray string = "Nokia";
      QCryptographicHash hasher(QCryptographicHash::Sha1);
      hasher.addData(string);
      

      返回最终的哈希值。

      QByteArray string1=hasher.result();
      

      还有Main.cpp例子

      #include <QtGui/QApplication>
      #include <QWidget>
      #include <QHBoxLayout>
      #include <QCryptographicHash>
      #include <QString>
      #include <QByteArray>
      #include <QLabel>
      
      int main(int argc, char *argv[])
      {
          QApplication a(argc, argv);
          QWidget *win=new QWidget();
          QHBoxLayout *lay=new QHBoxLayout();
          QLabel *lbl=new QLabel();
          QLabel *lbl1=new QLabel("Encrypted Text:");
          lbl1->setBuddy(lbl);
          QByteArray string="Nokia";
          QCryptographicHash *hash=new QCryptographicHash(QCryptographicHash::Md4);
          hash->addData(string);
          QByteArray string1=hash->result();
          lbl->setText(string1); // TODO: use e.g. toHex or toBase64
          lay->addWidget(lbl1);
          lay->addWidget(lbl);
          win->setLayout(lay);
          win->setStyleSheet("* { background-color:rgb(199,147,88); padding: 7px ;   color:rgb(255,255,255)}");
          win->showMaximized();
          return a.exec();
      }
      

      【讨论】: