Openssl-RSA加解密实现demo

本文介绍了如何在 Kali Linux 虚拟机中使用 OpenSSL 库通过 C++ 实现RSA加解密。通过生成密钥、提取公钥、写入文件、加密和解密文件等步骤,演示了RSA非对称加密的过程,并验证了加密解密后的信息一致性。
摘要由CSDN通过智能技术生成

Openssl
RSA加解密实现
VM ware 15.5pro
Linux虚拟机:Kali (debian 10.x 64)

  1. C++程序实现对字符串的RSA加密
//图中用到的命令解析:
openssl genrsa -out prikey.pem 1024
//openssl生成密钥(同时含有私钥公钥),-out参数指定输出文件目的地(在此是prikey.pem),1024为长度

openssl rsa -in prikey.pem -pubout -out pubkey.pem
//提取出prikey.pem中的公钥,-in参数指示了此条命令的输入文件(也就是从哪里提取公钥)

vi demo.cpp
//编写demo cpp代码

g++ demo.cpp -o demo -lcrypto
//g++编译 -o参数指定可执行文件的文件名(如不指定,默认名称a.out)
./demo
//执行上一步生成的可执行文件,查看输出

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Demo信息加解密前后一致,成功

附:
g++ demo.cpp -o demo -lcrypto
g++编译执行demo.cpp代码:


#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/pem.h>

#include <iostream>
#include <string>
#include <cstring>
#include <cassert>
using namespace std;

//加密
std::string EncodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData )
{
   
	if (strPemFileName.empty() || strData.empty())
	{
   
		assert(false);
		return "";
	}
	FILE* hPubKeyFile = fopen(strPemFileName.c_str(), "rb");
	if( hPubKeyFile == NULL )
	{
   
		assert(false);
		return ""; 
	}
	std::string strRet;
	RSA* pRSAPublicKey = RSA_new();
	if(PEM_read_RSA_PUBKEY(hPubKeyFile, &pRSAPublicKey, 0, 0) == NULL)
	{
   
		assert(false);
		return "";
	}

	int nLen = RSA_size(pRSAPublicKey);
	char* pEncode = new char[nLen + 1];
	int ret = RSA_public_encrypt(strData.length(), (const unsigned char*)strData.c_str(), (unsigned char*)pEncode, pRSAPublicKey, RSA_PKCS1_PADDING);
	if (ret >= 0)
	{
   
		strRet = std::string(pEncode, ret);
	}
	delete[] pEncode;
	RSA_free(pRSAPublicKey);
	fclose(hPubKeyFile);
	CRYPTO_cleanup_all_ex_data(); 
	return strRet;
}

//解密
std::string DecodeRSAKeyFile( const std::string& strPemFileName, const std::string& strData )
{
   
	if (strPemFileName.empty() || strData.empty())
	{
   
		assert(false);
		return "";
	}
	FILE* hPriKeyFile = fopen(strPemFileName.c_str(),"rb");
	if( hPriKeyFile == NULL )
	{
   
		assert(false);
		return "";
	}
	std::string strRet;
	RSA* pRSAPriKey = RSA_new();
	if(PEM_read_RSAPrivateKey(hPriKeyFile, &pRSAPriKey, 0, 0) == NULL)
	{
   
		assert(false);
		return "";
	}
	int nLen = RSA_size(pRSAPriKey);
	char* pDecode = new char[nLen+1];

	int ret = RSA_private_decrypt(strData.length(), (const unsigned char*)strData.c_str(), (unsigned char*)pDecode, pRSAPriKey, RSA_PKCS1_PADDING);
	if(ret >= 0)
	{
   
		strRet = std::string((char*)pDecode, ret);
	}
	delete [] pDecode
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Chi Z犬里

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

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

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

打赏作者

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

抵扣说明:

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

余额充值