Skip to main content

Featured Post

How to use Tabs in ASP.NET CORE

I want to show Components in a tabs , so first of all create few components. In this project we have three components, First View Component  public class AllViewComponent : ViewComponent     {         private readonly UserManager<ApplicationUser> _userManager;         public AllViewComponent(UserManager<ApplicationUser> userManager)         {             _userManager = userManager;         }         public async Task<IViewComponentResult> InvokeAsync()         {             List<StudentViewModel> allUsers = new List<StudentViewModel>();             var items = await _userManager.Users.ToListAsync();             foreach (var item in items)             {                 allUsers.Add(new StudentViewModel {Id=item.Id, EnrollmentNo = item.EnrollmentNo, FatherName = item.FatherName, Name = item.Name, Age = item.Age, Birthdate = item.Birthdate, Address = item.Address, Gender = item.Gender, Email = item.Email });             }            

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 Post

Polynomial representation using Linked List for Data Structure in 'C'

Polynomial representation using Linked List The linked list can be used to represent a polynomial of any degree. Simply the information field is changed according to the number of variables used in the polynomial. If a single variable is used in the polynomial the information field of the node contains two parts: one for coefficient of variable and the other for degree of variable. Let us consider an example to represent a polynomial using linked list as follows: Polynomial:      3x 3 -4x 2 +2x-9 Linked List: In the above linked list, the external pointer ‘ROOT’ point to the first node of the linked list. The first node of the linked list contains the information about the variable with the highest degree. The first node points to the next node with next lowest degree of the variable. Representation of a polynomial using the linked list is beneficial when the operations on the polynomial like addition and subtractions are performed. The resulting polynomial can also

How to use Tabs in ASP.NET CORE

I want to show Components in a tabs , so first of all create few components. In this project we have three components, First View Component  public class AllViewComponent : ViewComponent     {         private readonly UserManager<ApplicationUser> _userManager;         public AllViewComponent(UserManager<ApplicationUser> userManager)         {             _userManager = userManager;         }         public async Task<IViewComponentResult> InvokeAsync()         {             List<StudentViewModel> allUsers = new List<StudentViewModel>();             var items = await _userManager.Users.ToListAsync();             foreach (var item in items)             {                 allUsers.Add(new StudentViewModel {Id=item.Id, EnrollmentNo = item.EnrollmentNo, FatherName = item.FatherName, Name = item.Name, Age = item.Age, Birthdate = item.Birthdate, Address = item.Address, Gender = item.Gender, Email = item.Email });             }            

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