/// <summary> /// Encrypts the data using the public key /// </summary> /// <param name="value"></param> /// <param name="publicKey"></param> /// <returns></returns> public static string Encrypt(byte[] valueBytes, string publicKey) { // use rsa to encrypt the key using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); // for large keys use symmetric encryption, and then just use RSA to encrypt the key. if (valueBytes.Length > 50) { // generate a symmetric new key. byte[] key = new byte[20]; using (var randomNumberGenerator = RandomNumberGenerator.Create()) { randomNumberGenerator.GetBytes(key); } var encryptedBytes = EncryptString.Encrypt(valueBytes, key); var encryptedKey = rsa.Encrypt(key, true); // combine the rsa and encrypted bytes. // the combined string contains length (4 bytes), encryptedKey (length), encryptedBytes (remainder) var combinedValue = new byte[4 + encryptedKey.Length + encryptedBytes.Length]; Array.Copy(BitConverter.GetBytes(encryptedKey.Length), combinedValue, 4); Array.Copy(encryptedKey, 0, combinedValue, 4, encryptedKey.Length); Array.Copy(encryptedBytes, 0, combinedValue, 4 + encryptedKey.Length, encryptedBytes.Length); return(Convert.ToBase64String(combinedValue)); } else { var encryptedValue = rsa.Encrypt(valueBytes, true); var combinedValue = new byte[4 + encryptedValue.Length]; Array.Copy(ZeroBytes, 0, combinedValue, 0, 4); Array.Copy(encryptedValue, 0, combinedValue, 4, encryptedValue.Length); return(Convert.ToBase64String(combinedValue)); } } }