Authenticate the Valid User Via User id and MD5 Hashed Password

Introduction

This article shows how to validate the user through the user ID and hashed password saved in the database.

For the demonstration, I will

  1. Get a table in the database that stores the login credentials of the user.
  2. Create a website and add an MD5 conversion file of JavaScript.
  3. Add a page to the website with 2 textboxes for User ID and Password and a save button.
  4. Add a reference to the MD5 conversion file on the page and create a JavaScript function to convert the plain password to the hashed password.
  5. Add the code on the page load for creating salt and send it the JavaScript function via attribute add of the save button and on a button click event to match the data.

Note. To understand more about the first point go to my previous article "Generate the Client-side Hash Via MD5 Algorithm and Saving to Database (http://www.c-sharpcorner.com/UploadFile/a20beb/generate-the-client-side-hash-via-md5-algorithm-and-saving-t/).

Step 1. I have a table named "LoginTable" in the database, that stores the login credentials of the user.

LoginTable

Step 2. Create a website and add an MD5 conversion file of JavaScript.

  1. Create an empty website named "LoginCredentials".
    Login Credentials
  2. Add a new folder on the root and name it "Scripts". Add the "md5.js" into the "Scripts" folder.

Note. You can find the "md5.js" in the attached file.

Attached file

Step 3. Add a page in the website with 2 textboxes for User ID and Password and Login button.

  1. Add a page named "Login.aspx".
    Login button
  2. Add some controls on the page like,
    • The text box for the user id is named "txtUserID".
    • The text box for a password is named "txtpwd" with TextMode="Password".
    • Button for login named "btn_login" with "on click" event.
      Add textBox in web page

Step 4. Add a reference to the MD5 conversion file on the page and create a JavaScript function to convert the plain password to the hashed password.

  1. Add the reference of the MD5 conversion file on the page as in the following.
    <script src="Scripts/md5.js"></script>
    
  2. Create a JavaScript function to convert the plain password to the hashed password in the "head" section of the page as in the following.
    <script type="text/javascript">
        
    function HashPwdwithSalt(salt) {
        
        if (document.getElementById("txtpwd").value != "") {
            
            document.getElementById("txtpwd").value = hex_md5(document.getElementById("txtpwd").value);
            
            document.getElementById("txtpwd").value = hex_md5(document.getElementById("txtpwd").value + salt);
            
        }
    }
    </script>
    

Note. The "hex_md5" function exists in the "md5.js" file and here the conversion of the password into a hash has been done 2 times. First for converting the plain text to a hash then the hashed text to a hash with salt, just for safety purposes. If I do the single hash and match it on the server side then any hacker can get the hash password and easily enter it into the system.

Hash password

Step 5. Add the code on the page load for creating the salt and send it the JavaScript function via attribute add of the save button and on the button click event to save the data.

  1. Create a method that will get the size of the salt and return a salt after generation via the random number generator cryptography technique.
    private string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);
        return Convert.ToBase64String(buff);
    }
    
  2. Get the value in the salt variable and add the JavaScript function with the salt parameter via the attribute add of the save button.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //get the 5 digit salt
            string salt = CreateSalt(5);
    
            //Save the salt in session variable
            Session["salt"] = salt.ToString();
    
            //Add the JS function call to button with a parameter
            btn_login.Attributes.Add("onclick", "return HashPwdwithSalt('" + salt.ToString() + "');");
        }
    }
    
  3. Get the hash password from the database, if the user id is valid. Then hash it again with an already generated salt and match it with the filled-in password by the user to check the authenticity of the user on the login button click event.
    protected void btn_login_Click(object sender, EventArgs e)
    {
        if (txtUserID.Text != "" && txtpwd.Text != "")
        {
            //Get the password from the database
            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                string commandText = "Select pwd from LoginTable where UserID='" + txtUserID.Text + "'";
                cmd.CommandText = commandText;
                cmd.CommandType = CommandType.Text;
                object pwd = cmd.ExecuteScalar();
                cmd.Dispose();
                connection.Close();
    
                // create the hash of the correct password with salt
                string hashed_pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd.ToString().ToLower() + Session["salt"].ToString(), "md5");
    
                // match the both passwords
                if (hashed_pwd.ToLower().Equals(txtpwd.Text))
                {
                    Response.Write("Valid User");// redirect to Home page
                }
                else
                {
                    Response.Write("Invalid User");
                    return;
                }
            }
        }
    }
    

JavaScript code for login button

At Run Time

After running the page, check both of the conditions for authenticity for correct and incorrect passwords.

For Valid User

type the valid user ID and password.

Valid user

Note. Here the valid User ID is "Admin" and the password is "abcd1234".

Result

Then the output will be a valid user.

Output

For Invalid User

If I fill in the wrong password then it will give a different output.

Here I have provided "123" as the password.

Invalid user

Result

Then the output will be "Invalid user".

Result


Similar Articles