请用qt写出对字符串加解密的例子
时间: 2023-05-19 14:05:59 浏览: 175
加密解密字符串的例子
当然可以,以下是一个使用Qt实现字符串加解密的例子:
```cpp
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QCryptographicHash>
QString encrypt(QString plaintext, QString key)
{
QByteArray keyBytes = key.toUtf8();
QByteArray plaintextBytes = plaintext.toUtf8();
QByteArray hash = QCryptographicHash::hash(keyBytes, QCryptographicHash::Sha256);
QByteArray iv = QCryptographicHash::hash(keyBytes, QCryptographicHash::Md5);
QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::CBC);
encryption.setKey(hash);
encryption.setIV(iv);
QByteArray ciphertextBytes = encryption.encode(plaintextBytes);
QString ciphertext = QString::fromUtf8(ciphertextBytes.toBase64());
return ciphertext;
}
QString decrypt(QString ciphertext, QString key)
{
QByteArray keyBytes = key.toUtf8();
QByteArray ciphertextBytes = QByteArray::fromBase64(ciphertext.toUtf8());
QByteArray hash = QCryptographicHash::hash(keyBytes, QCryptographicHash::Sha256);
QByteArray iv = QCryptographicHash::hash(keyBytes, QCryptographicHash::Md5);
QAESEncryption decryption(QAESEncryption::AES_256, QAESEncryption::CBC);
decryption.setKey(hash);
decryption.setIV(iv);
QByteArray plaintextBytes = decryption.decode(ciphertextBytes);
QString plaintext = QString::fromUtf8(plaintextBytes);
return plaintext;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString plaintext = "Hello, world!";
QString key = "mysecretkey";
QString ciphertext = encrypt(plaintext, key);
qDebug() << "Ciphertext:" << ciphertext;
QString decryptedText = decrypt(ciphertext, key);
qDebug() << "Decrypted text:" << decryptedText;
return a.exec();
}
```
这个例子使用了Qt的QCryptographicHash和QAESEncryption类来实现AES-256加解密。在加密时,我们使用SHA-256哈希算法和MD5哈希算法来生成密钥和初始化向量。在解密时,我们使用相同的密钥和初始化向量来解密密文。
阅读全文