Openssl
RSA加解密实现
VM ware 15.5pro
Linux虚拟机:Kali (debian 10.x 64)
- 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;
RSA_free