AES Encryption in .Net (Dot Net) c#

Code Snippets 4 U

Note : We should use ‘using’ statements so that we don’t have to close streams manually. Also we are using streams to encrypt the data instead of direct methods because it will take care of appropriate function to use.

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

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {

            string email = "[email protected]";
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            // generate the key of 256 bit (allowed are 128 bits and 256 bits)
            Random rand = new Random();

            byte[] key = new byte[16];
            for (int i = 0; i < 16; i++)
            {
                key[i] = (byte)rand.Next();
            }

            // allowed block size of IV (Initialization vector) is 128 bits
            byte[] IV = new byte[16];
            for (int i = 0; i < 16; i++)
            {
                IV[i] = (byte)rand.Next();
            }

            aes.Key = key;
            aes.IV = IV;

            byte[] output;
            using (MemoryStream mStream = new MemoryStream())
            using (ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV))
            using (CryptoStream cStream = new CryptoStream(mStream, encrypt, CryptoStreamMode.Write))
            {
                using (StreamWriter sWriter = new StreamWriter(cStream))
                    sWriter.Write(email);
                output = mStream.ToArray();
            }

            using (MemoryStream mStream = new MemoryStream(output))
            using (ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, aes.IV))
            using (CryptoStream cStream = new CryptoStream(mStream, decrypt, CryptoStreamMode.Read))
            using (StreamReader sReader = new StreamReader(cStream))
                email = sReader.ReadToEnd();

            Console.WriteLine(email);
            Console.ReadKey();
        }
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

fifty eight + = sixty