// (c) 2006 Richard Grimes // www.grimes.demon.co.uk using System; using System.Security.Cryptography; using System.Text; using System.IO; class App { static void Main() { Rijndael r = Rijndael.Create(); string phrase = "daisy, daisy, give me your answer to"; PasswordDeriveBytes pdb = new PasswordDeriveBytes(phrase, new byte[0]); r.Key = pdb.GetBytes(r.KeySize >> 3); string data = "The quick brown fox jumps over the lazy dog."; ICryptoTransform en = r.CreateEncryptor(); byte[] input = Encoding.ASCII.GetBytes(data); input = CryptoTransform(input, en, true); Console.WriteLine(Encoding.ASCII.GetString(input)); ICryptoTransform de = r.CreateDecryptor(); byte[] output = CryptoTransform(input, de, false); Console.WriteLine(Encoding.ASCII.GetString(output)); } static byte[] CryptoTransform(byte[] input, ICryptoTransform en, bool bEncrypt) { MemoryStream sInput = new MemoryStream(input); MemoryStream sOutput = new MemoryStream(); CryptoStream cs; if (bEncrypt) { cs = new CryptoStream(sOutput, new ToBase64Transform(), CryptoStreamMode.Write); cs = new CryptoStream(cs, en, CryptoStreamMode.Write); } else { cs = new CryptoStream(sOutput, en, CryptoStreamMode.Write); cs = new CryptoStream(cs, new FromBase64Transform(), CryptoStreamMode.Write); } byte[] buffer = new byte[1024]; while (true) { int read = sInput.Read(buffer, 0, buffer.Length); if (read == 0) break; cs.Write(buffer, 0, read); } cs.FlushFinalBlock(); cs.Clear(); return sOutput.ToArray(); } }