Monday, 24 August 2020

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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";
           }
 
                             
        }
    }
}

UserReg

If you are implementing this code with database then do like this,at insert time code will be like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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;
            }
        }
 
    }
}

Forget Password

For forget password you can do like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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 ForgetPassword : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string flag = CheckUserId();
        if (flag == "true")
        {
            using (SqlCommand cmd = new SqlCommand("update tblLogin set Password=@Password where UserId=@UserId", 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);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                lblmsg.Text = "Your password has been Updated Sucessfully";
            }
        }
      
    }
 
 
    private string CheckUserId()
    {
        using (SqlCommand cmd = new SqlCommand("Select UserId from tblLogin where UserId=@UserId", con))
        {
            cmd.Parameters.AddWithValue("@UserId", txtUserId.Text);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count == 1)
            {
                 
                return "true";
            }
            else
            {
                lblmsg.Text = "Invalid UserId";
                txtPassword.Text = string.Empty;
                return "false";
            }
            
        }
    }
    
}


No comments:

Post a Comment