AES Cryptography

Contains the code for AES encryption and decryption in C#.

   1: public byte [] EncryptText(string plainData)

   2:         {

   3:             RijndaelManaged rij = new RijndaelManaged();

   4:             

   5:             rij.GenerateKey();

   6:             _key = rij.Key;

   7:  

   8:             rij.GenerateIV();

   9:             _intializationVector = rij.IV;

  10:  

  11:             ICryptoTransform encryptor = rij.CreateEncryptor(_key, _intializationVector);

  12:  

  13:             using (MemoryStream msEncrypt = new MemoryStream())

  14:             {

  15:                 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

  16:                 {

  17:                     using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))

  18:                     {

  19:                         swEncrypt.Write(plainData);

  20:                     }

  21:  

  22:                     return msEncrypt.ToArray();

  23:                 }

  24:             }

  25:  

  26:         }

  27:  

  28:  

  29:         public string  DecryptText(byte [] encrytedData)

  30:         {

  31:             RijndaelManaged rij = new RijndaelManaged();

  32:  

  33:             ICryptoTransform decryptor = rij.CreateDecryptor(_key, _intializationVector);

  34:  

  35:             using (MemoryStream msDecrypt = new MemoryStream(encrytedData))

  36:             {

  37:                 using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

  38:                 {

  39:                     using (StreamReader srDecrypt = new StreamReader(csDecrypt))

  40:                     {

  41:                         return srDecrypt.ReadToEnd();

  42:                     }

  43:                 }

  44:             }

  45:         }

  46:         

  47:     }

Advertisements

Comments are closed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: