openssl 自行编译,可参考网上教程
RSA私钥解密算法证明 有兴趣可以自行了解
可参考博客:RSA加解密
下面是个人笔记,有需要用到自行修改;
RSA.h
#ifndef _RSA_H_
#define _RSA_H_
#include <iostream>
#include <string.h>
std::string GetExefilePath(char *keyfile);
void priEn_pubDe_test();
void pubEn_priDe_test();
// 公钥加密
std::string rsa_pub_encrypt(const std::string &clearText, std::string &pubKey);
// 私钥解密
std::string rsa_pri_decrypt(const std::string &clearText, std::string &priKey);
#endif
RSA.cpp
#include "stdafx.h"
#include "RSA.h"
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <Shlwapi.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
//#include "BASE64/Base64Ex.h"
//#include "BASE64/base64.h"
//#pragma comment(lib, "Shlwapi.lib")
//1024 ->密文长度 128-11 ,明文128
//2048 ->密文长度 256 ,明文256
//4096 ->密文长度 512 ,明文512
// ---- rsa非对称加解密 ---- //
#define KEY_LENGTH 1024 // 密钥长度
#define PUB_KEY_FILE "pubkey.pem" // 公钥路径
#define PRI_KEY_FILE "prikey.pem" // 私钥路径
// 函数方法生成密钥对
void generateRSAKey(std::string strKey[2])
{
// 公私密钥对
size_t pri_len;
size_t pub_len;
char *pri_key = NULL;
char *pub_key = NULL;
// 生成密钥对
RSA *keypair = RSA_generate_key(KEY_LENGTH, RSA_F4, NULL, NULL);
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
PEM_write_bio_RSAPublicKey(pub, keypair);
// 获取长度
pri_len = BIO_pending(pri);
pub_len = BIO_pending(pub);
// 密钥对读取到字符串
pri_key = (char *)malloc(pri_len + 1);
pub_key = (char *)malloc(pub_len + 1);
BIO_read(pri, pri_key, pri_len);
BIO_read(pub, pub_key, pub_len);
pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';
// 存储密钥对
strKey[0] = pub_key;
strKey[1] = pri_key;
// 存储到磁盘(这种方式存储的是begin rsa public key/ begin rsa private key开头的)
FILE *pubFile = fopen(PUB_KEY_FILE, "w");
if (pubFile == NULL)
{
//assert(false);
return;
}
fputs(pub_key, pubFile);
fclose(pubFile);
FILE *priFile = fopen(PRI_KEY_FILE, "w");
if (priFile == NULL)
{
//assert(false);
return;
}
fputs(pri_key, priFile);
fclose(priFile);
// 内存释放
RSA_free(keypair);
BIO_free_all(pub);
BIO_free_all(pri);
free(pri_key);
free(pub_key);
}
//std::string strdata = "0123456789_abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string strdata = "0123456789_abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789_abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789_abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-01234