Skip to main content

Save Password using Encoding, decoding and Hashing Techniques in ASP.NET

Introduction

Plain text change in unreadable format known as encoding. And reverse of it known as decoding. Change a plain text into cipher text using any key known as hashing. There are lots of techniques available in hashing.
Here we take a simple example of among. First we start from Encoding.


How to change plain text into cipher text (Unreadable format)

first of all, take a string variable, after that take a byte array, which size is equal to string Length. Look like

String str = "Hello World";
Byte [] encode = new Byte[str.Length];

Get Bytes of string value using getBytes( ) method of UTF8 encoding. Now, your code look like

encode = Encoding.UTF8.GetBytes(str);
Now, change encoded byte array into Base64String.

encodepwd = Convert.ToBase64String(encode); // here encodepwd is the string variable.
Store encoded password is stored in encodepwd variable.

How to Change cipher Text into Plain Text

First of all, encoded string convert into specified string format, which is equivalent 8-bit unsigned integer array using FromBase64String ( ) method. count number of characters using GetCharCount( ) of byte array like.
 byte[] todecode = Convert.FromBase64String(decryptpwd);
 int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
Decode sequence of byte into set of characters using GetChars( ) method.

 char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

Complete source code

 <form id="form1" runat="server">
    <div>
    
        <table style="width:100%;">
            <tr>
                <td class="style1">
                    UserName</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" Caption="Encrypted Data">
    </asp:GridView>
    <br />
    <asp:GridView ID="GridView2" runat="server" Caption="Decrypted Data" 
        onrowdatabound="GridView2_RowDataBound">
    </asp:GridView>
    <br />
    </form>

Business Logic Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
            bindgridview2();
            
        }

    }

    private void bindgridview2()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView2.DataSource = ds;
        GridView2.DataBind();
      
    }

    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = encodepassword(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
        bindgridview2();


    }

    private string encodepassword(string p)
    {
        string encodepwd = string.Empty;
        byte[] encode = new byte[p.Length];
        encode = Encoding.UTF8.GetBytes(p);
        encodepwd = Convert.ToBase64String(encode);
        return encodepwd;

    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row .RowType ==DataControlRowType .DataRow)
        {
            string decryptpwd = e.Row.Cells[2].Text;
            e.Row.Cells[2].Text = decryptpassword(decryptpwd);
        }
        
    }

    private string decryptpassword(string decryptpwd)
    {
        string decryptpass = string.Empty;
        UTF8Encoding encode = new UTF8Encoding();
        Decoder decode = encode.GetDecoder();
        byte[] todecode = Convert.FromBase64String(decryptpwd);
        int charcountvariable = decode.GetCharCount(todecode, 0, todecode.Length);
        char[] decode_array = new char[charcountvariable];
        decode.GetChars(todecode, 0, todecode.Length,decode_array ,0);

        decryptpass = new String(decode_array);
        return decryptpass;
       
    }
    
}

Code Generate the following output

Save Password using Encoding, decoding

MD5 Hashing Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;

    public _Default()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();


    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindgridview1();
           
            
        }

    }
    private void bindgridview1()
    {
        con.Open();
        cmd.CommandText = "select * from [user]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();
        

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pwdtxt = getMd5Hash(TextBox2.Text);
        con.Open();
        cmd.CommandText = "insert into [user](userName,Password)values(@us,@pw)";
        cmd.Parameters.AddWithValue("@us", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", pwdtxt);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        con.Close();
        bindgridview1();
     


    }

    private static string getMd5Hash(string p)
    {
        MD5 md5Hasher = MD5.Create();

       
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(p));

       
        StringBuilder sBuilder = new StringBuilder();

       
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

      
        return sBuilder.ToString();

    }
  
}

Code Generate the following output

hashed password

Comments

Popular posts from this blog

difference between structure and union in C Language

In c language article we will see the difference between union and structure. Both are the user define datatype in c language. See the table which is mentioned below: ASP.NET Video Tutorial Series Structure Union1.The keywordstruct is used to define a structure 1. The keyword union is used to define a union. 2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum ofsizes of its members. The smaller members may end with unused slack bytes. 2. When a variable is associated with a union, thecompiler allocates thememory by considering the size of the largest memory. So, size of union is equal to the size of largest member. 3. Each member within a structure is assigned unique storage area of location. 3. Memory allocated is shared by individual members of union. 4. The address of each member will be in ascending order This indicates that memory for each member will start at different offset v…

Difference between Linear search and Binary Search in c language

SQL Video Channel : Download all SQL Video



Binary Search Linear Search Works only on sorted items. such as  1,2,3,4,5,6  etc
Works on sorted as well as unsorted items. 12,4,5,3,2,1 etc Very efficient if the items are sorted Very efficient if the items are less and present in the beginning of the list. such as Suppose your list items are : 12,3,4,5,1 and you want to search 12 number then you get beginning in the list. Works well with arrays and not on linked lists. Works with arrays and linked lists.
Number of comparisons are less More number of comparisons are required if the items are present in the later part of the array or its elements are more.

Memory representation of Linked List Data Structures in C Language

Memory representation of Linked List

             In memory the linked list is stored in scattered cells (locations).The memory for each node is allocated dynamically means as and when required. So the Linked List can increase as per the user wish and the size is not fixed, it can vary.

               Suppose first node of linked list is allocated with an address 1008. Its graphical representation looks like the figure shown below:


      Suppose next node is allocated at an address 506, so the list becomes,



  Suppose next node is allocated with an address with an address 10,s the list become,


The other way to represent the linked list is as shown below:




 In the above representation the data stored in the linked list is “INDIA”, the information part of each node contains one character. The external pointer root points to first node’s address 1005. The link part of the node containing information I contains 1007, the address of next node. The last node …