rsa linux 加密工具,用openssl进行rsa的加密与解密(linux,C++版)

转自 : http://blog..net/small_qch/article/details/19330211

初学openssl库,写了一例子,记录一下。PS:openssl和openssl库的安装就不说了,网上一大把

1:输入命令,生成公钥和私钥(1024位)

openssl genrsa -out prikey.pem 1024openssl rsa -in privkey.pem -pubout -out pubkey.pem

2:C++小程序

[cpp] view

plaincopy

print?

//demo.cpp

// g++ demo.cpp -o demo -lcrypto

#include 

#include 

#include 

#include 

#include 

#include 

#include 

usingnamespacestd;

//加密

std::string EncodeRSAKeyFile( conststd::string& strPemFileName,conststd::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"";

}

intnLen = RSA_size(pRSAPublicKey);

char* pEncode =newchar[nLen + 1];

intret = RSA_public_encrypt(strData.length(), (constunsignedchar*)strData.c_str(), (unsignedchar*)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();

returnstrRet;

}

//解密

std::string DecodeRSAKeyFile( conststd::string& strPemFileName,conststd::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"";

}

intnLen = RSA_size(pRSAPriKey);

char* pDecode =newchar[nLen+1];

intret = RSA_private_decrypt(strData.length(), (constunsignedchar*)strData.c_str(), (unsignedchar*)pDecode, pRSAPriKey, RSA_PKCS1_PADDING);

if(ret >= 0)

{

strRet = std::string((char*)pDecode, ret);

}

delete[] pDecode;

RSA_free(pRSAPriKey);

fclose(hPriKeyFile);

CRYPTO_cleanup_all_ex_data();

returnstrRet;

}

intmain()

{

//原文

conststring one ="skl;dfhas;lkdfhslk;dfhsidfhoiehrfoishfsidf";

cout <

//密文(二进制数据)

string two = EncodeRSAKeyFile("pubkey.pem", one);

cout <

//顺利的话,解密后的文字和原文是一致的

string three = DecodeRSAKeyFile("prikey.pem", two);

cout <

return0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值