openssl rsa密钥

#include <boost/asio/ssl.hpp>
#include
#if defined(WINDOWS)
#if (OPENSSL_VERSION_NUMBER >= 0x10101000L)
#pragma comment(lib,“libcrypto.lib”)
#pragma comment(lib,“libssl.lib”)
#else
#pragma comment(lib,“libeay32.lib”)
#pragma comment(lib,“ssleay32.lib”)
#endif
#endif

#define KEY_LENGTH 2048 // 密钥长度
#define PUB_KEY_FILE “./pubkey.pem” // 公钥路径
#define PRI_KEY_FILE “./prikey.pem” // 私钥路径

/*
制造密钥对:私钥和公钥
/
void GenerateRSAKey(std::string& out_pub_key, std::string& out_pri_key)
{
size_t pri_len = 0; // 私钥长度
size_t pub_len = 0; // 公钥长度
char
pri_key = nullptr; // 私钥
char
pub_key = nullptr; // 公钥
// 生成密钥对
RSA* keypair = RSA_generate_key(KEY_LENGTH, RSA_3, 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);
// 注意------生成第1种格式的公钥
//PEM_write_bio_RSAPublicKey(pub, keypair);
// 注意------生成第2种格式的公钥(此处代码中使用这种)
PEM_write_bio_RSA_PUBKEY(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’;
out_pub_key = pub_key;
out_pri_key = pri_key;
// 将公钥写入文件
std::ofstream pub_file(PUB_KEY_FILE, std::ios::out);
if (!pub_file.is_open())
{
perror(“pub key file open fail:”);
return;
}
pub_file << pub_key;
pub_file.close();
// 将私钥写入文件
std::ofstream pri_file(PRI_KEY_FILE, std::ios::out);
if (!pri_file.is_open())
{
perror(“pri key file open fail:”);
return;
}
pri_file << pri_key;
pri_file.close();
// 释放内存
RSA_free(keypair);
BIO_free_all(pub);
BIO_free_all(pri);
free(pri_key);
free(pub_key);
}
int main()
{
std::string pub_key;
std::string pri_key;
GenerateRSAKey(pub_key, pri_key);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹平华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值