1.需要应用的库文件
pro文件添加:
INCLUDEPATH += $$PWD/openssl/
LIBS += -L$$PWD/./lib -llibeay32
LIBS += -L$$PWD/./lib -lssleay32
2.使用示例
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define BEGIN_RSA_PUBLIC_KEY "BEGIN RSA PUBLIC KEY"
#define BEGIN_RSA_PRIVATE_KEY "BEGIN RSA PRIVATE KEY"
#define BEGIN_PUBLIC_KEY "BEGIN PUBLIC KEY"
#define BEGIN_PRIVATE_KEY "BEGIN PRIVATE KEY"
#define KEY_LENGTH 1024
/*!
* \brief 公钥加密(非对称)
* \param strPlainData 需要加密数据
* \return
*/
QString pcTools::rsaPubEncrypt(const QString &strPlainData)
{
//默认公钥
m_publicEncryptKey = "-----BEGIN PUBLIC KEY-----\n"
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5mcB+jiv2m4e7M7UBN8IiIDsS\n"
"W6NizcGuIr2gzwrhyoRb9hz8fg4fgcRmmmsssSswBeH7Y5xSaD5uHf9aoArRk2iH\n"
"po3lj9rXXwHdACudsIRh+Zt1/Z1MRsa0RfSCEOgMmyceWVe7GepPyg9sVr+PvFPh\n"
"NpZntrzfcBauB/+2iQIDAQsB\n"
"-----END PUBLIC KEY-----\n";
QByteArray pubKeyArry = m_publicEncryptKey.toUtf8();
uchar* pPubKey = (uchar*)pubKeyArry.data();
BIO* pKeyBio = BIO_new_mem_buf(pPubKey, pubKeyArry.length());
if (pKeyBio == nullptr)
{
return "";
}
RSA* pRsa = RSA_new();
if (m_publicEncryptKey.contains(BEGIN_RSA_PUBLIC_KEY))
{
pRsa = PEM_read_bio_RSAPublicKey(pKeyBio, nullptr, nullptr, nullptr);
}
else
{
pRsa = PEM_read_bio_RSA_PUBKEY(pKeyBio, nullptr, nullptr, nullptr);
}
if (pRsa == nullptr)
{
BIO_free_all(pKeyBio);
return "";
}
int nLen = RSA_size(pRsa);
char* pEncryptBuf = new char[nLen];
memset(pEncryptBuf, 0, nLen);
//加密
QByteArray plainDataArry = strPlainData.toUtf8();
int nPlainDataLen = plainDataArry.length();
uchar* pPlainData = (uchar*)plainDataArry.data();
int nSize = RSA_public_encrypt(nPlainDataLen,
pPlainData,
(uchar*)pEncryptBuf,
pRsa,
RSA_PKCS1_PADDING);
QString strEncryptData = "";
if (nSize >= 0)
{
QByteArray arry(pEncryptBuf, nSize);
strEncryptData = arry.toBase64();
}
//释放内存
delete[] pEncryptBuf;
BIO_free_all(pKeyBio);
RSA_free(pRsa);
return strEncryptData;
}
注:公钥或者密钥 使用字符串传输都要加 \n 不然会导致 PEM_read_bio_RSA_PUBKEY或者PEM_read_bio_RSAPublicKey 函数返回空值。
参考示例:https://blog.csdn.net/u011029517/article/details/79392522