Exemple #1
0
static bool DecodeFromFile(const char* filename, RSA::PrivateKey& key)
{
	try {
		ByteQueue queue;
		FileSource file(filename, true);
		file.TransferTo(queue);
		queue.MessageEnd();
		key.BERDecodePrivateKey(queue, false, queue.MaxRetrievable());
		return key.Validate(rng, 3);
	} catch (...) {
		return false;
	}
}
Exemple #2
0
int main(int argc, char** argv)
{
	std::ios_base::sync_with_stdio(false);

	// http://www.cryptopp.com/docs/ref/class_auto_seeded_random_pool.html
	AutoSeededRandomPool rnd;

	try
	{
		// http://www.cryptopp.com/docs/ref/rsa_8h.html
		RSA::PrivateKey rsaPrivate;
		rsaPrivate.GenerateRandomWithKeySize(rnd, 1024);

		RSA::PublicKey rsaPublic(rsaPrivate);

    if(!rsaPrivate.Validate(rnd, 3)) {
      throw runtime_error("Validation failed");
    }

		SavePrivateKey("rsa-private.key", rsaPrivate);
		SavePublicKey("rsa-public.key", rsaPublic);

		cout << "Successfully generated and saved RSA keys:" << endl;
    cout << "Values:" << endl;
    cout << "N: " << rsaPrivate.GetModulus() << endl;
    cout << "E: " << rsaPrivate.GetPublicExponent() << endl;
    cout << "D: " << rsaPrivate.GetPrivateExponent() << endl;
	}

	catch(CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		return -2;
	}

	catch(std::exception& e)
	{
		cerr << e.what() << endl;
		return -1;
	}

	return 0;
}
/*
 * generate the RSA public key and private key in separate file
 */
void MyRSA::GenerateRSAKey(unsigned int keyLength, const char *privFilename,
                           const char *pubFilename)
{   AutoSeededRandomPool rng;
    RSA::PrivateKey priv;
    priv.GenerateRandomWithKeySize(rng, 1024);
    if (!priv.Validate(rng, 3))
    {
        throw("RSA key generation failed");
    }
	HexEncoder privFile(new FileSink(privFilename));
	priv.DEREncode(privFile);
	privFile.MessageEnd();
    
    
    RSA::PublicKey pub;
    pub.AssignFrom(priv);
	HexEncoder pubFile(new FileSink(pubFilename));
	pub.DEREncode(pubFile);
	pubFile.MessageEnd();
}