麻痹的找了好久,真恶心!
#include <stdio.h> #include <stdlib.h> #ifdef WIN32 #include <windows.h> #endif #include "openssl/rsa.h" #include "openssl/pem.h" #include "Base64.h" #ifdef WIN32 #pragma comment(lib,"User32.lib") #pragma comment(lib,"Advapi32.lib") #pragma comment(lib,"Gdi32.lib") #pragma comment(lib,"libeay32.lib") #pragma comment(lib,"ssleay32.lib") #endif // 私钥解密 std::string rsa_pri_decrypt(const std::string &cipherText, const std::string &priKey) { std::string strRet; RSA *rsa = RSA_new(); BIO *keybio; keybio = BIO_new_mem_buf((unsigned char *)priKey.c_str(), -1); // 此处有三种方法 // 1, 读取内存里生成的密钥对,再从内存生成rsa // 2, 读取磁盘里生成的密钥对文本文件,在从内存生成rsa // 3,直接从读取文件指针生成rsa rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL); int len = RSA_size(rsa); char *decryptedText = (char *)malloc(len + 1); memset(decryptedText, 0, len + 1); // 解密函数 int ret = RSA_private_decrypt(cipherText.length(), (const unsigned char*)cipherText.c_str(), (unsigned char*)decryptedText, rsa, RSA_PKCS1_PADDING); if (ret >= 0) strRet = std::string(decryptedText, ret); // 释放内存 free(decryptedText); BIO_free_all(keybio); RSA_free(rsa); return strRet; }