Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void CryptLib::GenerateRandomRSAKeyPair(string& publicKey, string& privateKey, int keySize)
- {
- //Generate params
- AutoSeededRandomPool rng;
- InvertibleRSAFunction params;
- //256 - 4096
- params.Initialize(rng, 512);
- //Generate Keys
- RSA::PrivateKey privKey(params);
- RSA::PublicKey pubKey(params);
- //Encode keys to Base64
- string encodedPriv, encodedPub;
- Base64Encoder privKeySink(new StringSink(encodedPriv));
- privKey.DEREncode(privKeySink);
- privKeySink.MessageEnd();
- Base64Encoder pubKeySink(new StringSink(encodedPub));
- pubKey.DEREncode(pubKeySink);
- pubKeySink.MessageEnd();
- publicKey = encodedPub;
- privateKey = encodedPriv;
- }
- const string CryptLib::EncryptRSA(const string& plaintext, const string& publicKey)
- {
- //Decode public key
- RSA::PublicKey pbKeyDecoded;
- StringSource ss2(publicKey, true, new Base64Decoder);
- pbKeyDecoded.BERDecode(ss2);
- //Encrypt message
- //Encrypt string
- Integer e = Integer((const byte*)plaintext.data(), plaintext.size());
- Integer crypted = pbKeyDecoded.ApplyFunction(e);
- //Encode it as base64
- size_t len = crypted.MinEncodedSize();
- string crpt;
- crpt.resize(len);
- crypted.Encode((byte*)crpt.data(), crpt.size(), Integer::UNSIGNED);
- string encodedCrypt;
- StringSource ss((byte*)crpt.c_str(), crpt.length(), true,
- new Base64Encoder(
- new StringSink(encodedCrypt), false
- )
- );
- //return it
- return encodedCrypt;
- }
- const string CryptLib::DecryptRSA(const string& cipher, const string& privateKey)
- {
- //decode private key
- RSA::PrivateKey pvKeyDecoded;
- StringSource ss3(privateKey, true, new Base64Decoder);
- pvKeyDecoded.BERDecode(ss3);
- //decrypt the cipher
- string decodedCipher;
- StringSource sb(cipher, true,
- new Base64Decoder(
- new StringSink(decodedCipher)
- )
- );
- //Convert binary string to Integer
- Integer normalCipher((byte*)decodedCipher.c_str(), decodedCipher.length());
- //feed the recovered cipher
- AutoSeededRandomPool rng;
- Integer d = pvKeyDecoded.CalculateInverse(rng, normalCipher);
- //decode it to string
- string recovered;
- size_t req = d.MinEncodedSize();
- recovered.resize(req);
- d.Encode((byte*)recovered.data(), recovered.size());
- //return it
- return recovered;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement