find a location for property in a new city

Thursday, 8 September 2011

AES encryption and decryption in .NET

AES essentials

Start your class like this:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Utils
{
 public static class EncryptionHelper
 {
    static private byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                                            15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
    static private byte[] iv16Bit = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };

AES Encryption

Add the following method for encrypting with AES:
public static string AesEncryption(string dataToEncrypt)
{
   var bytes = Encoding.Default.GetBytes(dataToEncrypt);
   using (var aes = new AesCryptoServiceProvider())
   {
    using (var ms = new MemoryStream())
    using (var encryptor = aes.CreateEncryptor(key, iv16Bit))
    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {
     cs.Write(bytes, 0, bytes.Length);
     cs.FlushFinalBlock();
     var cipher = ms.ToArray();
     return Convert.ToBase64String(cipher);
    }
   }
}

AES Decryption

The next method will allow decryption of your data
public static string AesDecryption(string dataToDecrypt)
{
   var bytes = Convert.FromBase64String(dataToDecrypt);
   using (var aes = new AesCryptoServiceProvider())
   {
    using (var ms = new MemoryStream())
    using (var decryptor = aes.CreateDecryptor(key, iv16Bit))
    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
    {
     cs.Write(bytes, 0, bytes.Length);
     cs.FlushFinalBlock();
     var cipher = ms.ToArray();
     return Encoding.UTF8.GetString(cipher);
    }
   }
}

Follow britishdev on Twitter

6 comments:

  1. Recently I am working on this only but was having problem with key leng. After following this I think I have caught the problem to where I was getting wrong.

    ReplyDelete
  2. Hey really much appreciate your work really you have done a great work and providing useful information over here. Thanks for sharing

    ReplyDelete
  3. Motifz Designer Lawn. 1, 2 & 3 Piece Unstitched Premium Embroidered Lawn 2019, Premium embroidered Lawn, Premium lawn, Premium lawn 2019, Motifz, Premium lawn in Pakistan. Shipping worldwide. Stitching option available.

    ReplyDelete
  4. Buy online wholesale printed custom cbd boxes and packaging at easy prices and shipping worldwide, with 24/7 customer support. Get a free custom quote now!!

    ReplyDelete
  5. Blackbird packaging provide you with any size, shape design, custom e liquid boxes sooner than any other packaging competitor in the market

    ReplyDelete