Sunday, 25 June 2017

CryptoStream

Streams are basically channels that can perform one of three basic functions:

  • Read - Take data out of a stream and use it
  • Write - put data into a stream
  • Seek - move through the stream to look for something 

Streams can feed each other, you can take the output from one stream and run it into another. If you would want to encrypt data that goes through a stream you could either encrypt it before, or you can chain your stream with the CryptoStream.

using System;
using System.IO;
using System.Security.Cryptography;

namespace pc.CryptoStreamExample
{
    class Program
    {
        static void Encrypt(string Data, out byte[] Key, out byte[] IV)
        {
            using (var aesAlgorythm = new AesManaged())
                try
                {
                    aesAlgorythm.GenerateIV();
                    IV = aesAlgorythm.IV;
                    aesAlgorythm.GenerateKey();
                    Key = aesAlgorythm.Key;

                    using (var encryptor = aesAlgorythm.CreateEncryptor())
                    using (var fs = new FileStream(@"c:\securedData.txt", FileMode.Create))
                    using (var cs = new CryptoStream(fs, encryptor, CryptoStreamMode.Write))
                    using (var sw = new StreamWriter(cs))
                        sw.Write(Data);
                }
                finally
                {
                    aesAlgorythm.Clear();
                }
        }

        static void Decrypt(byte[] Key, byte[] IV)
        {
            using (var aesAlgorythm = new AesManaged())
                try
                {
                    using (var decryptor = aesAlgorythm.CreateDecryptor(Key, IV))
                    using (var fs = new FileStream(@"c:\securedData.txt", FileMode.Open))
                    using (var cs = new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
                    using (var sr = new StreamReader(cs))
                        Console.WriteLine(sr.ReadToEnd());
                }
                finally
                {
                    aesAlgorythm.Clear();
                }
        }
        static void Main(string[] args)
        {
            var data = "Hello world, this is my secret data i want encrypted";
            byte[] key;
            byte[] iv;
            Encrypt(data, out key, out iv);
            Decrypt(key, iv);
        }
    }
}

in the above we have two methods that do the work, encrypt and decrypt using our file and crypto stream and with our stream reader and writer to write and read encypted data to our textfile.