#include <QtCore/QCoreApplication> #include <QtCore/QString> #include <QtCore/QByteArray> #include <QtCore/QDebug> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h>

static QByteArray base64Decode(const QString &input) { QByteArray data = QByteArray::fromBase64(input.toLatin1()); return data; }

static QByteArray rsaDecrypt(const QByteArray &input, const QByteArray &privateKey) { RSA *rsa = RSA_new(); const char *cPrivateKey = privateKey.constData(); BIO bio = BIO_new_mem_buf((void) cPrivateKey, -1); rsa = PEM_read_bio_RSAPrivateKey(bio, &rsa, NULL, NULL); if (!rsa) { qDebug() << 'Failed to load private key'; return QByteArray(); }

QByteArray result;
int inputLength = input.length();
int MAX_ENCRYPT_BLOCK = RSA_size(rsa) - 11;
int offSet = 0;
while (inputLength > offSet) {
    QByteArray cache;
    if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
        cache.resize(MAX_ENCRYPT_BLOCK);
    } else {
        cache.resize(inputLength - offSet);
    }
    memcpy(cache.data(), input.constData() + offSet, cache.length());
    QByteArray out(cache.length() + EVP_MAX_BLOCK_LENGTH, 0);
    int len = RSA_private_decrypt(cache.length(), (const unsigned char*) cache.constData(),
                                   (unsigned char*) out.data(), rsa, RSA_PKCS1_PADDING);
    if (len == -1) {
        qDebug() << 'Failed to decrypt data';
        RSA_free(rsa);
        return QByteArray();
    }
    out.resize(len);
    result.append(out);
    offSet += MAX_ENCRYPT_BLOCK;
}
RSA_free(rsa);
return result;

}

QString decrypt(QString str, QString privateKey) { QByteArray inputByte = base64Decode(str); QByteArray decoded = base64Decode(privateKey);

QByteArray out = rsaDecrypt(inputByte, decoded);
return QString::fromUtf8(out.constData(), out.length());

}

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

QString str = 'encrypted string';
QString privateKey = 'private key in PEM format';

QString decrypted = decrypt(str, privateKey);
qDebug() << 'Decrypted string:' << decrypted;

return a.exec();

}

QT+openssl实现Java RSA解密代码

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

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