使用Crypto++进行RSA私钥解密

// g++ -g3 -ggdb -O0 -DDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread
// g++ -g -O2 -DNDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread

#include "osrng.h"
#include "modes.h"
#include "base64.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include "cryptlib.h"
#include "rsa.h"
#include "filters.h"

using namespace std;
using namespace CryptoPP;

// 从字符串加载公钥或私钥
template <typename Key>
const Key loadKeyBase64FromString(const std::string& str)
{
  Key key;
  CryptoPP::StringSource source(str.c_str(), true, new CryptoPP::Base64Decoder);
  key.Load(source);
  return key;
}

// 使用RSA解密,其中密文使用base64编码
string decryptRSA(const string &cipher, const string &priKeyStr) {
	AutoSeededRandomPool prng;
	// 加载私钥
	RSA::PrivateKey privateKey = loadKeyBase64FromString<RSA::PrivateKey>(priKeyStr);
	std::string encrypted;

	// 密文使用base64解码,获取源数据
	StringSink *sink = new StringSink(encrypted);
	StringSource(cipher.c_str(), true, new Base64Decoder(sink));

	// 解密
	std::string decrypted;
	RSAES_PKCS1v15_Decryptor d(privateKey);
	StringSource(encrypted, true,
		   new PK_DecryptorFilter(prng, d,
					  new StringSink(decrypted)));
	return decrypted;
}


int test_rsa_main()
{
	cout << "----------------" << endl
		<< "Start RSA test_rsa_main:" << endl;

	string cipherText = "cipher";
	string priKeyStr = "prikey";

	std::cout << "密文encrypted:" << cipherText<< endl;
	string decrypted = decryptRSA(cipherText, priKeyStr);
	std::cout << "解密decrypted:" << decrypted << endl;
	return 0;
}

注:上面的key需要修改为正确的私钥

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值