I'm trying to implement RSA Algorithm using Crypto++ under Ubuntu 12.04 I managed to implement both encryption and decryption in one program. Is there any way so that I can separate the encryption and decryption? What I want is when I call the encryption part, it will create a ciphertext as an output, and then when I call the decryption part, it will take the ciphertext from encryption as an input, and If I call the decryption part first, then it will create an error message.
This is the code for encryption and decryption:
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::hex;
#include <string>
using std::string;
#include "rsa.h"
using CryptoPP::RSA;
#include "integer.h"
using CryptoPP::Integer;
#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;
int main(int argc, char** argv)
{
// Pseudo Random Number Generator
AutoSeededRandomPool rng;
///////////////////////////////////////
// Generate Parameters
CryptoPP::InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rng, 3072);
///////////////////////////////////////
// Generated Parameters
const Integer& n = params.GetModulus();
const Integer& p = params.GetPrime1();
const Integer& q = params.GetPrime2();
const Integer& d = params.GetPrivateExponent();
const Integer& e = params.GetPublicExponent();
cout << endl;
///////////////////////////////////////
// Create Keys
RSA::PrivateKey privateKey(params);
RSA::PublicKey publicKey(params);
/////////////////////////////////////////////////////////
string message, recovered;
Integer m, c, r;
cout << endl;
cout << "RSA Algorithm" << endl;
cout << "message: " ;
std::cin >> message;
// Treat the message as a big endian array
m = Integer((const byte *)message.data(), message.size());
cout << "plaintext: " << hex << m << endl << endl;
cout << "ENCRYPTION" << endl;
// Encrypt
c = publicKey.ApplyFunction(m);
cout << "cipherthext: " << hex << c << endl << endl;
cout << "DECRYPTION" << endl;
// Decrypt
r = privateKey.CalculateInverse(rng, c);
cout << "plaintext: " << hex << r << endl;
// Round trip the message
size_t req = r.MinEncodedSize();
recovered.resize(req);
r.Encode((byte *)recovered.data(), recovered.size());
cout << "recovered: " << recovered << endl;
return 0;
}
I appreciate any help. Thank you.