1. 首先安装 OpenSSL 库,可以使用以下命令:
sudo apt-get install libssl-dev
  1. 在 QT 项目中添加 OpenSSL 库,可以在 .pro 文件中添加以下内容:
LIBS += -lssl -lcrypto
  1. 在需要使用 RSA 加解密的地方,引入 OpenSSL 库并使用以下代码:
// 初始化加密解密密钥
RSA* rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);

// 获取公钥和私钥
BIO* bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPublicKey(bio, rsa);
size_t pubKeyLength = BIO_pending(bio);
char* pubKey = new char[pubKeyLength + 1];
BIO_read(bio, pubKey, pubKeyLength);
pubKey[pubKeyLength] = '\0';
BIO_free_all(bio);

bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
size_t priKeyLength = BIO_pending(bio);
char* priKey = new char[priKeyLength + 1];
BIO_read(bio, priKey, priKeyLength);
priKey[priKeyLength] = '\0';
BIO_free_all(bio);

// 加密
int encryptLen = RSA_size(rsa);
unsigned char* encryptData = new unsigned char[encryptLen];
memset(encryptData, 0, encryptLen);
RSA_public_encrypt(strData.length() + 1, (const unsigned char*)strData.toStdString().c_str(), encryptData, rsa, RSA_PKCS1_PADDING);

// 解密
int decryptLen = RSA_size(rsa);
unsigned char* decryptData = new unsigned char[decryptLen];
memset(decryptData, 0, decryptLen);
RSA_private_decrypt(encryptLen, encryptData, decryptData, rsa, RSA_PKCS1_PADDING);
QString decryptStr = QString::fromStdString((char*)decryptData);

// 释放资源
RSA_free(rsa);
delete[] pubKey;
delete[] priKey;
delete[] encryptData;
delete[] decryptData;

其中,RSA_generate_key() 函数用于生成 RSA 密钥对,PEM_write_bio_RSAPublicKey() 和 PEM_write_bio_RSAPrivateKey() 函数用于将公钥和私钥转换成 PEM 格式,RSA_public_encrypt() 和 RSA_private_decrypt() 函数用于加解密数据,RSA_free() 函数用于释放 RSA 密钥对的资源。需要注意的是,加密数据的长度不能超过密钥长度减去 11 个字节(RSA_PKCS1_PADDING 填充模式下),否则会报错。

QT 使用 OpenSSL 实现 RSA 加解密

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

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