using System; using System.IO; using System.Text; using System.Security.Cryptography; using System.Net; public class main { public static void Main(string[] args) { byte[] key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16}; byte[] IV; string original = "This is a test."; ASCIIEncoding textConverter = new ASCIIEncoding(); RijndaelManaged myRijndael = new RijndaelManaged(); byte[] encrypted; byte[] toEncrypt; byte[] encLen; myRijndael.Mode = CipherMode.CBC; //Create a new initialization vector. myRijndael.GenerateIV(); IV = myRijndael.IV; //Get an encryptor. ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); // I'm using base64 encoding CryptoStream b64 = new CryptoStream(msEncrypt, new ToBase64Transform(), CryptoStreamMode.Write); b64.Write(IV, 0, IV.Length); // Write IV before encryption CryptoStream csEncrypt = new CryptoStream(b64, encryptor, CryptoStreamMode.Write); //Convert the data to a byte array. toEncrypt = textConverter.GetBytes(original); // Get the string length and convert to bytes in network order encLen = BitConverter.GetBytes( IPAddress.HostToNetworkOrder(toEncrypt.Length)); csEncrypt.Write(encLen, 0, encLen.Length); //Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. encrypted = msEncrypt.ToArray(); // Here we write to console, but of course you // may want to include it in an XML response Console.WriteLine(textConverter.GetString(encrypted)); } }