// (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(BitConverter.ToString(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 = new CryptoStream(sOutput, en, CryptoStreamMode.Write); SHA256 sha256 = SHA256.Create(); Stream data = null; if (bEncrypt) data = new CryptoStream(sInput, sha256, CryptoStreamMode.Read); else data = sInput; byte[] buffer = new byte[1024]; while (true) { int read = data.Read(buffer, 0, buffer.Length); if (read == 0) break; cs.Write(buffer, 0, read); } if (bEncrypt) cs.Write(sha256.Hash, 0, sha256.Hash.Length); cs.FlushFinalBlock(); cs.Clear(); if (!bEncrypt) { byte[] hash = new byte[sha256.HashSize >> 3]; sOutput.Position = sOutput.Length - hash.Length; sOutput.Read(hash, 0, hash.Length); sOutput.Position = 0; sOutput.SetLength(sOutput.Length - hash.Length); byte[] newHash = sha256.ComputeHash(sOutput); for (int x = 0; x < hash.Length; ++x) { if (hash[x] != newHash[x]) throw new CryptographicException("Data is corrupt!"); } } return sOutput.ToArray(); } }