使用OpenSSL进行RSA非对称加密(C++版本)
Posted 好儿郎-志在四方
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用OpenSSL进行RSA非对称加密(C++版本)相关的知识,希望对你有一定的参考价值。
运行环境
源代码运行环境,Widows 10,Qt Creator 5.14.1 MingW。
环境准备
关于OpenSSL,既可以下载源代码自己编译,也可以下载已经编译好的库,参见文章:https://blog.csdn.net/liang19890820/article/details/51658574
编译好之后,有如下目录结果:
需在 .pro工程文件中配置引用库和依赖路径:
INCLUDEPATH += $$PWD/openssl/include
DEPENDPATH += $$PWD/openssl/include
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/openssl/lib/ -llibcrypto
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/openssl/lib/ -llibcrypto
源代码
#include "openssl/ssl.h"
#include "openssl/rsa.h"
#define BEGIN_RSA_PUBLIC_KEY "BEGIN RSA PUBLIC KEY"
#define BEGIN_PUBLIC_KEY "BEGIN PUBLIC KEY"
#define PUBLIC_KEY "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYN5V1VTcOsHxBgccNPgujoNim5wpEaIy4q1zniuth23yKj+kiIJ47ltxBske7FfX4mTzxGKTfAXUacSWlXZ6oihd/wKjPvkjV4RyJjN9sejlofyaZDBXffWE8EL6UhBu3k9O+fPR/7USgqZ5JJE1QkeztigkR8d3Z5gmN7n8K3wIDAQAB"
QString rsa_pub_encrypt(const QString &cleardata)
{
QString pubkey=PUBLIC_KEY;
pubkey.insert(0, "-----BEGIN PUBLIC KEY-----\\n");
pubkey.append("\\n-----END PUBLIC KEY-----\\n");
QByteArray pubKeyArry = pubkey.toUtf8();
uchar* pPubKey = (uchar*)pubKeyArry.data();
BIO* pKeyBio = BIO_new_mem_buf(pPubKey, pubKeyArry.length());
if (pKeyBio == NULL){
return "";
}
RSA* pRsa = RSA_new();
if ( pubkey.contains(BEGIN_RSA_PUBLIC_KEY) ){
pRsa = PEM_read_bio_RSAPublicKey(pKeyBio, &pRsa, NULL, NULL);
}else{
pRsa = PEM_read_bio_RSA_PUBKEY(pKeyBio, &pRsa, NULL, NULL);
}
if ( pRsa == NULL ){
BIO_free_all(pKeyBio);
return "";
}
int nLen = RSA_size(pRsa);
char* pEncryptBuf = new char[nLen];
memset(pEncryptBuf, 0, nLen);
QByteArray clearDataArry = cleardata.toUtf8();
int nClearDataLen = clearDataArry.length();
uchar* pClearData = (uchar*)clearDataArry.data();
int nSize = RSA_public_encrypt(nClearDataLen,
pClearData,
(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;
}
以上是关于使用OpenSSL进行RSA非对称加密(C++版本)的主要内容,如果未能解决你的问题,请参考以下文章