I have c# code which uses BouncyCastle library to do RSA encryption:
public string EncryptData(string publicKey, string data)
{
try
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(data);
int srclen = bytesToEncrypt.Length;
//Prepare encryption engine
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
//Initialize Key
using (var txtreader = new StringReader(publicKey))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
//Encrypt in loop
byte[] complete = new byte[0];
int src_block_size = encryptEngine.GetInputBlockSize();
for (int idx = 0; idx < srclen; idx += src_block_size)
{
int data_len = srclen - idx;
if (data_len > src_block_size)
{
data_len = src_block_size;
}
var encryptedChunk = encryptEngine.ProcessBlock(bytesToEncrypt, idx, data_len);
complete = CombineByteArrays(complete, encryptedChunk);
}
var finalString = Convert.ToBase64String(complete);
return finalString;
}
catch (InvalidCipherTextException)
{
}
}
As you can see it chunks the data into blocks and encrypts each block. When I encrypt the data I can see that the finalstring
is a variable size (please note that finalString
is basically a base64 encoding of the encrypted bytes). Not sure what is the factor deciding the length and if it is a set pattern that I can rely on or it is indefinite. I need to make sure that the finalString
is within a limit (number of characters).
The size of an encrypted RSA block is dictated by the key size. The amount of data that can be encrypted in a RSA block is at the same time also dependent of the size of the RSA key minus the amount of data taken up by the padding.
Generally RSA should not be used for bulk encryption as it's quite slow (could be a factor 1000) and have an overhead on each block due to the padding (which you should use). If you actually need the benefit of the two key's in RSA, you should use a hybrid encryption approach. If you actually don't need the two keys, then you properly need to use a symmetric cipher like AES. Also, When using symmetric encryption you will get support for blocking right out of the box, as opposed to what you have with RSA.