Encrypt And Decrypt Value In ASP.NET Using C#

Here I am storing the values in database using LINQ queries as encrypted form.

We can encrypt or decrypt values using other algorithms.

But here, I am using SALT to encrypt and decrypt the values.

Step 1:

  1. public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)  
  2. {  
  3.     byte[] encryptedBytes = null;  
  4.   
  5.     // Set your salt here, change it to meet your flavor:  
  6.     byte[] saltBytes = passwordBytes;  
  7.     // Example:  
  8.     //saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };  
  9.   
  10.     using (MemoryStream ms = new MemoryStream())  
  11.     {  
  12.         using (RijndaelManaged AES = new RijndaelManaged())  
  13.         {  
  14.             AES.KeySize = 256;  
  15.             AES.BlockSize = 128;  
  16.   
  17.             var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);  
  18.             AES.Key = key.GetBytes(AES.KeySize / 8);  
  19.             AES.IV = key.GetBytes(AES.BlockSize / 8);  
  20.   
  21.             AES.Mode = CipherMode.CBC;  
  22.   
  23.             using (CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))  
  24.             {  
  25.                 cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);  
  26.                 cs.Close();  
  27.             }  
  28.             encryptedBytes = ms.ToArray();  
  29.         }  
  30.     }  
  31.   
  32.     return encryptedBytes;  
  33. }  
  34. public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)  
  35. {  
  36.     try  
  37.     {  
  38.         byte[] decryptedBytes = null;  
  39.         // Set your salt here to meet your flavor:  
  40.         byte[] saltBytes = passwordBytes;  
  41.         // Example:  
  42.         //saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };  
  43.   
  44.         using (MemoryStream ms = new MemoryStream())  
  45.         {  
  46.             using (RijndaelManaged AES = new RijndaelManaged())  
  47.             {  
  48.                 AES.KeySize = 256;  
  49.                 AES.BlockSize = 128;  
  50.   
  51.                 var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);  
  52.                 AES.Key = key.GetBytes(AES.KeySize / 8);  
  53.                 AES.IV = key.GetBytes(AES.BlockSize / 8);  
  54.   
  55.                 //AES.Mode = CipherMode.CBC;  
  56.   
  57.                 using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))  
  58.                 {  
  59.                     cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);  
  60.                     //If(cs.Length = ""  
  61.                     cs.Close();  
  62.                 }  
  63.                 decryptedBytes = ms.ToArray();  
  64.             }  
  65.         }  
  66.         return decryptedBytes;  
  67.     }  
  68.     catch (Exception Ex)  
  69.     {  
  70.         return null;  
  71.     }  
  72. }  
  73. public string Encrypt(string text, string pwd)  
  74. {  
  75.     byte[] originalBytes = Encoding.UTF8.GetBytes(text);  
  76.     byte[] encryptedBytes = null;  
  77.     byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);  
  78.   
  79.     // Hash the password with SHA256  
  80.     passwordBytes = SHA256.Create().ComputeHash(passwordBytes);  
  81.   
  82.     // Getting the salt size  
  83.     int saltSize = GetSaltSize(passwordBytes);  
  84.     // Generating salt bytes  
  85.     byte[] saltBytes = GetRandomBytes(saltSize);  
  86.   
  87.     // Appending salt bytes to original bytes  
  88.     byte[] bytesToBeEncrypted = new byte[saltBytes.Length + originalBytes.Length];  
  89.     for (int i = 0; i < saltBytes.Length; i++)  
  90.     {  
  91.         bytesToBeEncrypted[i] = saltBytes[i];  
  92.     }  
  93.     for (int i = 0; i < originalBytes.Length; i++)  
  94.     {  
  95.         bytesToBeEncrypted[i + saltBytes.Length] = originalBytes[i];  
  96.     }  
  97.   
  98.     encryptedBytes = AES_Encrypt(bytesToBeEncrypted, passwordBytes);  
  99.   
  100.     return Convert.ToBase64String(encryptedBytes);  
  101. }  
  102. public string Decrypt(string decryptedText, string pwd)  
  103. {  
  104.     byte[] bytesToBeDecrypted = Convert.FromBase64String(decryptedText);  
  105.     byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);  
  106.   
  107.     // Hash the password with SHA256  
  108.     passwordBytes = SHA256.Create().ComputeHash(passwordBytes);  
  109.   
  110.     byte[] decryptedBytes = AES_Decrypt(bytesToBeDecrypted, passwordBytes);  
  111.   
  112.     if (decryptedBytes != null)  
  113.     {  
  114.         // Getting the size of salt  
  115.         int saltSize = GetSaltSize(passwordBytes);  
  116.   
  117.         // Removing salt bytes, retrieving original bytes  
  118.         byte[] originalBytes = new byte[decryptedBytes.Length - saltSize];  
  119.         for (int i = saltSize; i < decryptedBytes.Length; i++)  
  120.         {  
  121.             originalBytes[i - saltSize] = decryptedBytes[i];  
  122.         }  
  123.         return Encoding.UTF8.GetString(originalBytes);  
  124.     }  
  125.     else  
  126.     {  
  127.         return null;  
  128.     }  
  129. }  
  130. private int GetSaltSize(byte[] passwordBytes)  
  131. {  
  132.     var key = new Rfc2898DeriveBytes(passwordBytes, passwordBytes, 1000);  
  133.     byte[] ba = key.GetBytes(2);  
  134.     StringBuilder sb = new StringBuilder();  
  135.     for (int i = 0; i < ba.Length; i++)  
  136.     {  
  137.         sb.Append(Convert.ToInt32(ba[i]).ToString());  
  138.     }  
  139.     int saltSize = 0;  
  140.     string s = sb.ToString();  
  141.     foreach (char c in s)  
  142.     {  
  143.         int intc = Convert.ToInt32(c.ToString());  
  144.         saltSize = saltSize + intc;  
  145.     }  
  146.   
  147.     return saltSize;  
  148. }  
  149. public byte[] GetRandomBytes(int length)  
  150. {  
  151.     byte[] ba = new byte[length];  
  152.     RNGCryptoServiceProvider.Create().GetBytes(ba);  
  153.     return ba;  
  154. }  
  155.   
  156. public bool Add(Movy movie)  
  157. {  
  158.     demo.Movies.InsertOnSubmit(movie);  
  159.     demo.SubmitChanges();  
  160.     return true;  
  161. }  
Step 2: Call that methods in .cs file.
  1. public partial class Add: System.Web.UI.Page   
  2. {  
  3.     /// <summary>  
  4.     /// Linq To SQL : Connection object.  
  5.     /// </summary>  
  6.     DemoDataContext demo = new DemoDataContext();  
  7.   
  8.     protected void Page_Load(object sender, EventArgs e)   
  9.     {  
  10.   
  11.     }  
  12.   
  13.     /// <summary>  
  14.     /// Button submit click event : Storing value in database as encrypted form  
  15.     /// </summary>  
  16.     /// <param name="sender"></param>  
  17.     /// <param name="e"></param>  
  18.     protected void btnSubmit_Click(object sender, EventArgs e) {  
  19.         try {  
  20.             if (txtName.Text != "")   
  21.             {  
  22.                 var m = new Movy   
  23.                 {  
  24.                     MovieName = new SecurityClass().Encrypt(txtName.Text, txtName.Text),  
  25.                 };  
  26.                 new SecurityClass().Add(m);  
  27.                 lblMessgae.Text = "Submitted successfully.";  
  28.                 txtName.Text = "";  
  29.             }  
  30.         }   
  31.         catch (Exception ex)   
  32.         {  
  33.             ex.Message.ToString();  
  34.         }  
  35.     }  
  36.   
  37.     protected void btnSearch_Click(object sender, EventArgs e) {  
  38.         try {  
  39.             if (txtSearchByName.Text != "")   
  40.             {  
  41.                 var movienameEncrypted = new SecurityClass().Encrypt(txtName.Text, txtName.Text);  
  42.                 if (movienameEncrypted != null)   
  43.                 {  
  44.                     string movienameDecrypt = new SecurityClass().Decrypt(movienameEncrypted, txtSearchByName.Text);  
  45.                     if (movienameDecrypt != null)   
  46.                     {  
  47.                         var Details = (from m in demo.Movies where movienameDecrypt == txtSearchByName.Text select new   
  48.                         {  
  49.                             UserName = m.Id  
  50.                         })  
  51.                         .FirstOrDefault();  
  52.                         if (Details != null)   
  53.                         {  
  54.                             lblMessgae.Text = "Movie exist into the database.";  
  55.                         }   
  56.                         else   
  57.                         {  
  58.                             lblMessgae.Text = "Not exist.";  
  59.                         }  
  60.                     }   
  61.                     else   
  62.                     {  
  63.                         lblMessgae.Text = "Not exist.";  
  64.                     }  
  65.                 }  
  66.             }  
  67.         }   
  68.         catch (Exception ex)   
  69.         {  
  70.             ex.Message.ToString();  
  71.         }  
  72.     }  
Screen:

output