public static byte[] Encrypt(
byte[] dataToEncrypt,
X509Certificate2 encryptingCertificate,
bool useOaep)
{
int plaintextBlockSize = GetPlainTextBlockSize(encryptingCertificate, useOaep);
int blockCount = ((dataToEncrypt.Length + 4) / plaintextBlockSize) + 1;
int plainTextSize = blockCount * plaintextBlockSize;
int cipherTextSize = blockCount * GetCipherTextBlockSize(encryptingCertificate, useOaep);
byte[] plainText = new byte[plainTextSize];
// encode length.
plainText[0] = (byte)((0x000000FF & dataToEncrypt.Length));
plainText[1] = (byte)((0x0000FF00 & dataToEncrypt.Length) >> 8);
plainText[2] = (byte)((0x00FF0000 & dataToEncrypt.Length) >> 16);
plainText[3] = (byte)((0xFF000000 & dataToEncrypt.Length) >> 24);
// copy data.
Array.Copy(dataToEncrypt, 0, plainText, 4, dataToEncrypt.Length);
byte[] buffer = new byte[cipherTextSize];
ArraySegment<byte> cipherText = Encrypt(new ArraySegment<byte>(plainText), encryptingCertificate, useOaep, new ArraySegment<byte>(buffer));
System.Diagnostics.Debug.Assert(cipherText.Count == buffer.Length);
return buffer;
}