在 QT 中使用 OpenSSL 库实现 AES 的 ECB 加解密过程的代码如下:

#include <openssl/aes.h>
#include <QDebug>

QString aes_encrypt(QString plaintext, QString key)
{
    QByteArray ba_plaintext = plaintext.toUtf8();
    QByteArray ba_key = key.toUtf8();

    int len = ba_plaintext.length();

    // 填充
    int padding = AES_BLOCK_SIZE - len % AES_BLOCK_SIZE;
    ba_plaintext.append(padding, padding);

    AES_KEY aes_key;
    if (AES_set_encrypt_key((const unsigned char *)ba_key.constData(), ba_key.length() * 8, &aes_key) < 0) {
        qDebug() << "AES_set_encrypt_key error!";
        return QString();
    }

    QByteArray ciphertext(len + padding, 0);

    for (int i = 0; i < len + padding; i += AES_BLOCK_SIZE) {
        AES_encrypt((const unsigned char *)(ba_plaintext.constData() + i),
                    (unsigned char *)(ciphertext.data() + i),
                    &aes_key);
    }

    return ciphertext.toBase64();
}

QString aes_decrypt(QString ciphertext, QString key)
{
    QByteArray ba_ciphertext = QByteArray::fromBase64(ciphertext.toUtf8());
    QByteArray ba_key = key.toUtf8();

    int len = ba_ciphertext.length();

    AES_KEY aes_key;
    if (AES_set_decrypt_key((const unsigned char *)ba_key.constData(), ba_key.length() * 8, &aes_key) < 0) {
        qDebug() << "AES_set_decrypt_key error!";
        return QString();
    }

    QByteArray plaintext(len, 0);

    for (int i = 0; i < len; i += AES_BLOCK_SIZE) {
        AES_decrypt((const unsigned char *)(ba_ciphertext.constData() + i),
                    (unsigned char *)(plaintext.data() + i),
                    &aes_key);
    }

    // 去除填充
    int padding = plaintext[plaintext.length() - 1];
    plaintext.chop(padding);

    return QString::fromUtf8(plaintext);
}

使用示例:

QString plaintext = "Hello, world!";
QString key = "1234567890123456";

QString ciphertext = aes_encrypt(plaintext, key);
qDebug() << "ciphertext:" << ciphertext;

QString decrypted_plaintext = aes_decrypt(ciphertext, key);
qDebug() << "decrypted_plaintext:" << decrypted_plaintext;

输出结果:

ciphertext: "Z9l0SbJq6h5z1Vz6f5+e/A=="
decrypted_plaintext: "Hello, world!"
``

原文地址: https://www.cveoy.top/t/topic/en8n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录