QT + openssl 实现rsa加解密
- 首先安装openssl库,可以使用以下命令:
sudo apt-get install libssl-dev
- 在QT项目中添加openssl库,可以在.pro文件中添加以下内容:
LIBS += -lssl -lcrypto
- 在需要使用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填充模式下),否则会报错
原文地址: https://www.cveoy.top/t/topic/eB0Y 著作权归作者所有。请勿转载和采集!