Encode Password using SHA256Managed Hashing Algorithm in .Net

 

.Net provides several hashing algorithms using the System.Security.Cryptography namespace and all hashing classes derived from HashAlgorithm base class. Most common algorithms used in .Net are MD5 and SHA1, but these are not recommended because these algorithms have lot of weaknesses. Latest recommended algorithms are SHA256 and SHA512 algorithms.

 

In this article we discuss about how to encode and compare password by using SHA256 algorithm. For example we have login form with username and password as admin and admin as shown below.

 

Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>SHA256 Algorithm in .NET</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lbl1" style="color:Red;" runat="server"></asp:Label><br />

        <label>User Name:</label><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />

        <label>Password:</label><asp:TextBox TextMode="Password" ID="txtPassword" runat="server"></asp:TextBox><br />

        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />&nbsp;&nbsp;

        <input type="reset" id="btnReset" name="btnReset" value="Clear" />

    </div>

    </form>

</body>

</html>

 

Default.aspx.cs

 

using System;

using System.Security.Cryptography;

using System.Text;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

       

    }

 

    protected void btnLogin_Click(object sender, EventArgs e)

    {

        try

        {

            //this is encoded value for password value admin

            string sPassword = "jGl25bVBBBW96Qi9Te4V37Fnqchz/Eu4qB9vKrRIqRg=";

            SHA256Managed sha256 = new SHA256Managed();

 

            byte[] input = Encoding.UTF8.GetBytes(txtPassword.Text);

            byte[] bPassword = sha256.ComputeHash(input);

 

            if (txtUserName.Text.Trim() == "admin" && sPassword == Convert.ToBase64String(bPassword))

                lbl1.Text = "Username and Password are correct";

            else

                lbl1.Text = "Username/Password are not correct";

        }

        catch (Exception ex)

        { }

    }

}

 

The encoded value of admin is jGl25bVBBBW96Qi9Te4V37Fnqchz/Eu4qB9vKrRIqRg= by using the SHA256Managed algorithm. We are comparing the user entered password field by encoding using SHA256Managed algorithm with the original value as shown above.

 

                                                                                                                                               Sha256Algorithm.zip (3.30 kb)