麻痹的找了很久,真噁心!html
#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; }
參考地址:http://www.javashuo.com/article/p-rbzbrcmu-mo.htmlwindows