// 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需要修改为正确的私钥