近期项目涉及跟服务器通讯,数据需要加密,就用服务端现有的RSA加密方式(非对称加密方式)
方式一、
手动编译openssl库然后拿到dll/lib导入然后使用。
方式二、
当时楼主使用的版本是这个:winx64 Openssl v1.1.1k 63MB Installer
安装完成找到目录:
C:Program FilesOpenSSL-Win64includeopenssl
libcrypto.lib
libssl.lib
两个库文件,具体怎么添加参考我blog里面lib的使用(windows之dll/lib导出)
配置好环境之后就开始加密了:
我这里是有服务端的公钥的所有直接配置即可。
//基于qt,win32更好不用转来转去
QString HttpFunc::rsaEncryData(const QString& plainText)//公钥加密
{
unsigned char encrypted[4098] = {};
RSA *rsa = NULL;
BIO *keybio;
keybio = BIO_new_mem_buf(pubLgoinKey, -1);
if (!keybio)
return QString();
rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);
if(!rsa)
return QString();
int encrypted_length = RSA_public_encrypt(plainText.size(), reinterpret_cast<const unsigned char *>(plainText.constData()), encrypted, rsa, RSA_PKCS1_PADDING);
BIO_free_all(keybio);
RSA_free(rsa);
return QString::fromUtf8((char*)encrypted);
}
QString HttpFunc::rsaDecryptData(const QString& decryptText)
{
unsigned char decrypted[4098] = {};
RSA *rsa = NULL;
BIO *keybio;
keybio = BIO_new_mem_buf("privateKey", -1);//demo这里是私钥解密
if (!keybio)
return QString();
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
if (!rsa)
return QString();
int decrypted_length = RSA_private_decrypt(decryptText.size(), reinterpret_cast<const unsigned char *>(decryptText.constData()), decrypted, rsa, RSA_PKCS1_PADDING);
BIO_free_all(keybio);
RSA_free(rsa);
return QString::fromUtf8((char*)decrypted);
}
注意公钥格式:
string pubKey=" -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAptoreKuW1O+Bb1u+O0LQ NAiaj5i0gbqi5uHCfcTxPIScoeidR/FaPFWpG3mHUCd7SfPKlSQ4H4FGwqkPrAJ8 tb6vfNAY7UPlStaWwCASBBBeHRIFySDIFQnIeXTcZqKgvCAkM3kudyKGMGfZyU6v SUCMUJbvtIKrSBpPFOaPF1EjfsTpcRjRwNUxjInvxyOmegdLSgg/NNV9AxUSpGX4 Fs5j3W4u4bfgoH6WiI7QLeVWpw+ZcynndtihPa2Y5rKgTDq1IYnniaYy+bTlWMPC us9AjL0qaM0oXKzUByIeA8cWQR99ewSLsEaa7mhpUZ1jg+fDQEqYfgvenfcOe5bn NQIDAQAB -----END PUBLIC KEY----- ";
参考博客:
https://blog.csdn.net/u011029517/article/details/79392522
https://blog.csdn.net/weixin_43255133/article/details/82860860
https://www.cnblogs.com/yuandaozhe/p/10114948.html