QT:AES-256-CBC Encrypt/Decript 根据 PHP 代码在 C++ 中

QT: AES-256-CBC Encrypt/Decript in C++ according to PHP Code

我有一个简单的 PHP encryption/decription AES-256-CBC 代码:

function safeEncrypt($token) {
    $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
    return openssl_encrypt($token, "aes-256-cbc", "passToCrypt", 0, $enc_iv) . "::" . bin2hex($enc_iv);
}
function safeDecrypt($token) {
    $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
    list($token, $enc_iv) = explode("::", $token);
    return openssl_decrypt($token, "aes-256-cbc", "passToCrypt", 0, hex2bin($enc_iv));
}

我正在 QML 应用程序中寻找 C++ 的相同方法。 到目前为止我有这个(我不知道如何处理 IV)

cryption.h:

#ifndef CRYPTION_H
#define CRYPTION_H

#include <QObject>
#include <QCryptographicHash>

class Cryption : public QObject
{
    Q_OBJECT
public:
    explicit Cryption(QObject *parent = nullptr);
    Q_INVOKABLE QString encrypt(QString strToEncrypt);
    Q_INVOKABLE QString decrypt(QString strToDecrypt);

private:
    QString method;
    QString key;
    QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::CBC);

signals:

public slots:

};

#endif // CRYPTION_H

cryption.cpp:

#include "cryption.h"
#include <QCryptographicHash>

Cryption::Cryption(QObject *parent) :
    QObject(parent)
{
    // Main Settings
    method = "aes-256-cbc";
    key = "passToCrypt";
}

QString Cryption::encrypt(QString strToEncrypt)
{
    QByteArray hashKey = QCryptographicHash::hash(key.toLocal8Bit(), QCryptographicHash::Sha256);
//  QByteArray hashIV = QCryptographicHash::hash(iv.toLocal8Bit(), QCryptographicHash::Md5);

    QByteArray encodeText = encryption.encode(strToEncrypt.toLocal8Bit(), hashKey, hashIV);
    return encodeText;
}

QString Cryption::decrypt(QString strToEncrypt)
{
    QByteArray hashKey = QCryptographicHash::hash(key.toLocal8Bit(), QCryptographicHash::Sha256);
//  QByteArray hashIV = QCryptographicHash::hash(iv.toLocal8Bit(), QCryptographicHash::Md5);

    QByteArray decodeText = encryption.decode(encodeText, hashKey, hashIV);
    QString decodedString = QString(encryption.removePadding(decodeText));
    return decodedString;
}

你能帮我完成吗? 主要是我不知道如何像 PHP 那样处理 IV(一些随机数,hex2bin)并且 IV 被保存到编码字符串中(ENCODED_STRING::USED_IV)所以IV可以稍后用于解码

在您的 PHP 代码中,initialization vector (IV) 是使用随机数生成器生成的。你可以用 Qt 做同样的事情。例如:

QByteArray iv = QByteArray(16, 0);
for(int i=0; i<16; ++i) {
    iv[i] = static_cast<char>(QRandomGenerator::system()->bounded(255));
}

相反,example you are following creates a string with whatever arbitrary text, and then calculates a MD5 hash of it. Using the above method is more direct, but you can do the same or generate a random string 在计算散列之前。