How to encrypt and decrypt password in asp.net using C#?
Hi
Storing password in database as encrypted form is the good practice to store password. We can do this task using so many algorithms.
Storing password in database as encrypted form is the good practice to store password. We can do this task using so many algorithms.
But here I m going to show you one of the easiest and complete secure method to encrypt and decrypt the password.
If you are storing password as encrypted formate using any algorithm without any salt value. Then hacker can easily decrypt the password using decryption method of same alogorith. But if you are using some salt value in your encrypted password then it will give completely strong encrtypted password.
Here we are mixing random salt value in encrtpted password.So It will be impossible to hack the data from database.
Here are some steps to do this tasks
Step1: Create one class i.e “Helper.cs” and write method like this.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Salt_Password_Sample { public class Helper { public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { // If salt is not specified, generate it. if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; } public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue) { // Convert base64-encoded hash value into a byte array. byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Make sure that hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Size of hash is based on the specified algorithm. switch (hashAlgorithm.ToUpper()) { case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. byte[] saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashAlgorithm, saltBytes); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); } } }
Step2: Call that method in code behind file like this.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Salt_Password_Sample { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void EncryptBtn_Click(object sender, EventArgs e) { string EPass = Helper.ComputeHash(TextBox1.Text, "SHA512", null); lblmsg.Text = EPass; } protected void Button1_Click(object sender, EventArgs e) { bool flag = Helper.VerifyHash(TextBox1.Text, "SHA512", lblmsg.Text); if (flag == true) { lblmsg1.Text = "You are the correct user"; } } } }
If you are implementing this code with database then do like this,at insert time code will be like this
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using Salt_Password_Sample; public partial class EmpReg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private void Cleartextbox() { txtAddress.Text = string.Empty; txtContactNo.Text = string.Empty; txtEmpName.Text = string.Empty; txtPassword.Text = string.Empty; txtUserId.Text = string.Empty; } protected void btnSubmit_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True")) { using (SqlCommand cmd = new SqlCommand("Insert into tblLogin(UserId,Password,EmpName,Address,ContactNo) values(@UserId,@Password,@EmpName,@Address,@ContactNo)", con)) { cmd.Parameters.AddWithValue("@UserId", txtUserId.Text); //Here i have implemented the code for doing encryption of password string ePass = Helper.ComputeHash(txtPassword.Text, "SHA512", null); cmd.Parameters.AddWithValue("@Password", ePass); cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text); cmd.Parameters.AddWithValue("@Address", txtAddress.Text); cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text); con.Open(); cmd.ExecuteNonQuery(); con.Close(); Cleartextbox(); lblmsg.Text = "Your profile has been created Sucessfully"; } } } }
At login time,we have to write code like this, But make ensure that UserId should be unique in database
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using Salt_Password_Sample; public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True")) { using(SqlCommand cmd=new SqlCommand("Select UserId,Password from tblLogin where UserId=@UserId",con)) { cmd.Parameters.AddWithValue("@UserId", txtUserName.Text); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); string userid = dt.Rows[0]["UserId"].ToString(); string password=dt.Rows[0]["Password"].ToString(); bool flag = Helper.VerifyHash(txtPassword.Text, "SHA512", password); if (userid == txtUserName.Text && flag == true) { Response.Redirect("Welcome.aspx"); } else { lblmsg.Text = "Invalid UserId or password"; } txtPassword.Text = string.Empty; txtUserName.Text = string.Empty; } } } }
Hi
ReplyDeleteJust doing copy paste of some other artical is not a good idea. At least could have to give reference to my blog.
Just doing copy paste of some other artical is not a good idea. At least you could have to give reference to my blog.
ReplyDeletehttp://chandradev819.wordpress.com/?s=How+to+encrypt+and+decrypt