RSA public/private key cryptography is limited in the amount of data that it can encrypt. With the commonly used v1.5 padding and the largest RSA key (currently 2048-bits), the maximum size of data that can be encrypted is 245 bytes.
If you want to encrypt and securely send more data than that you need to use a combination of asymmetric and symmetric encryption algorithms.
In practice, RSA is used to exchange an encrypted key between communicating endpoints that is then used to symmetrically encrypt/decrypt the large data.
Encryption by sender:
- Generate a cryptographically strong random key, K, of the length required for a symmetrical encryption technique such as Rijndael (maximum key size is 256 bits for Rijndael).
- Symmetrically encrypt your data using Rijndael using the random key generated in step 1.
- Using RSA, asymmetrically encrypt the random key generated in step 1 with the public part of the recipient’s RSA key.
- Send the RSA encrypted random key AND the encrypted data from steps 2 and 3 to recipient.
Decryption by recipient:
- Decrypt the encrypted key using your private RSA key.
- Decrypt the original data using the RSA-decrypted symmetric key from step 1.
Here’s how to generate a 2048 bit public/private key in C#:
using (var rsaProvider = new RSACryptoServiceProvider(2048))
{
rsaProvider.PersistKeyInCsp = false;
// Export public key to file
var publicKey = rsaProvider.ToXmlString(false);
using (publicKeyFile = File.CreateText(publicKeyFileName))
{
publicKeyFile.Write(publicKey);
}
// Export private/public key pair to file
var privateKey = rsaProvider.ToXmlString(true);
using (var privateKeyFile = File.CreateText(privateKeyFileName))
{
privateKeyFile.Write(privateKey);
}
}