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:
- public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
- {
- byte[] encryptedBytes = null;
- // Set your salt here, change it to meet your flavor:
- byte[] saltBytes = passwordBytes;
- // Example:
- //saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
- using (MemoryStream ms = new MemoryStream())
- {
- using (RijndaelManaged AES = new RijndaelManaged())
- {
- AES.KeySize = 256;
- AES.BlockSize = 128;
- var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
- AES.Key = key.GetBytes(AES.KeySize / 8);
- AES.IV = key.GetBytes(AES.BlockSize / 8);
- AES.Mode = CipherMode.CBC;
- using (CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
- {
- cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
- cs.Close();
- }
- encryptedBytes = ms.ToArray();
- }
- }
- return encryptedBytes;
- }
- public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
- {
- try
- {
- byte[] decryptedBytes = null;
- // Set your salt here to meet your flavor:
- byte[] saltBytes = passwordBytes;
- // Example:
- //saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
- using (MemoryStream ms = new MemoryStream())
- {
- using (RijndaelManaged AES = new RijndaelManaged())
- {
- AES.KeySize = 256;
- AES.BlockSize = 128;
- var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
- AES.Key = key.GetBytes(AES.KeySize / 8);
- AES.IV = key.GetBytes(AES.BlockSize / 8);
- //AES.Mode = CipherMode.CBC;
- using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
- {
- cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
- //If(cs.Length = ""
- cs.Close();
- }
- decryptedBytes = ms.ToArray();
- }
- }
- return decryptedBytes;
- }
- catch (Exception Ex)
- {
- return null;
- }
- }
- public string Encrypt(string text, string pwd)
- {
- byte[] originalBytes = Encoding.UTF8.GetBytes(text);
- byte[] encryptedBytes = null;
- byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);
- // Hash the password with SHA256
- passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
- // Getting the salt size
- int saltSize = GetSaltSize(passwordBytes);
- // Generating salt bytes
- byte[] saltBytes = GetRandomBytes(saltSize);
- // Appending salt bytes to original bytes
- byte[] bytesToBeEncrypted = new byte[saltBytes.Length + originalBytes.Length];
- for (int i = 0; i < saltBytes.Length; i++)
- {
- bytesToBeEncrypted[i] = saltBytes[i];
- }
- for (int i = 0; i < originalBytes.Length; i++)
- {
- bytesToBeEncrypted[i + saltBytes.Length] = originalBytes[i];
- }
- encryptedBytes = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
- return Convert.ToBase64String(encryptedBytes);
- }
- public string Decrypt(string decryptedText, string pwd)
- {
- byte[] bytesToBeDecrypted = Convert.FromBase64String(decryptedText);
- byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);
- // Hash the password with SHA256
- passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
- byte[] decryptedBytes = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
- if (decryptedBytes != null)
- {
- // Getting the size of salt
- int saltSize = GetSaltSize(passwordBytes);
- // Removing salt bytes, retrieving original bytes
- byte[] originalBytes = new byte[decryptedBytes.Length - saltSize];
- for (int i = saltSize; i < decryptedBytes.Length; i++)
- {
- originalBytes[i - saltSize] = decryptedBytes[i];
- }
- return Encoding.UTF8.GetString(originalBytes);
- }
- else
- {
- return null;
- }
- }
- private int GetSaltSize(byte[] passwordBytes)
- {
- var key = new Rfc2898DeriveBytes(passwordBytes, passwordBytes, 1000);
- byte[] ba = key.GetBytes(2);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < ba.Length; i++)
- {
- sb.Append(Convert.ToInt32(ba[i]).ToString());
- }
- int saltSize = 0;
- string s = sb.ToString();
- foreach (char c in s)
- {
- int intc = Convert.ToInt32(c.ToString());
- saltSize = saltSize + intc;
- }
- return saltSize;
- }
- public byte[] GetRandomBytes(int length)
- {
- byte[] ba = new byte[length];
- RNGCryptoServiceProvider.Create().GetBytes(ba);
- return ba;
- }
- public bool Add(Movy movie)
- {
- demo.Movies.InsertOnSubmit(movie);
- demo.SubmitChanges();
- return true;
- }
- public partial class Add: System.Web.UI.Page
- {
- /// <summary>
- /// Linq To SQL : Connection object.
- /// </summary>
- DemoDataContext demo = new DemoDataContext();
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- /// <summary>
- /// Button submit click event : Storing value in database as encrypted form
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnSubmit_Click(object sender, EventArgs e) {
- try {
- if (txtName.Text != "")
- {
- var m = new Movy
- {
- MovieName = new SecurityClass().Encrypt(txtName.Text, txtName.Text),
- };
- new SecurityClass().Add(m);
- lblMessgae.Text = "Submitted successfully.";
- txtName.Text = "";
- }
- }
- catch (Exception ex)
- {
- ex.Message.ToString();
- }
- }
- protected void btnSearch_Click(object sender, EventArgs e) {
- try {
- if (txtSearchByName.Text != "")
- {
- var movienameEncrypted = new SecurityClass().Encrypt(txtName.Text, txtName.Text);
- if (movienameEncrypted != null)
- {
- string movienameDecrypt = new SecurityClass().Decrypt(movienameEncrypted, txtSearchByName.Text);
- if (movienameDecrypt != null)
- {
- var Details = (from m in demo.Movies where movienameDecrypt == txtSearchByName.Text select new
- {
- UserName = m.Id
- })
- .FirstOrDefault();
- if (Details != null)
- {
- lblMessgae.Text = "Movie exist into the database.";
- }
- else
- {
- lblMessgae.Text = "Not exist.";
- }
- }
- else
- {
- lblMessgae.Text = "Not exist.";
- }
- }
- }
- }
- catch (Exception ex)
- {
- ex.Message.ToString();
- }
- }


diego loaizaPosted Sep 7, 2022, 8:37 PM
Would you have an example but without using the salt as a parameter?
Former memberPosted Nov 18, 2015, 4:38 AM
Thank Andrews, I'll Definitely Will Try. Thanks For The Suggestion :)
Christopher AndrewsPosted Nov 18, 2015, 4:07 AM
Cheers to the article! I have been using a tool called Redfly beta and it has been more than useful and easy to use. I suggest that you try it out too on www.redfly.io
Vikas JoshiPosted Sep 22, 2015, 3:35 PM
Thank you Sir :)
Santhakumar MunuswamyPosted Sep 22, 2015, 3:16 PM
Welcome
Santhakumar MunuswamyPosted Sep 22, 2015, 3:16 PM
Nice Start