Encrypt password using MD5 hash in asp.net

In this article I am going to explain how Encrypt password using MD5 hash in asp.net.

Encrypt password using MD5 hash in asp.net
Description:
MD5 is an acronym for Message-Digest 5. It is a fast and powerful method of increasing security to file transfers and message request transfers. To convert the text value into MD5 Hash value use the name System.Security.Cryptography.

Implementation:

HTML Markup:
<fieldset style="width:30%">
    <legend>Convert text (string) into MD5 hash</legend>
    <table>
    <tr><td>Enter Password : </td><td>
        <asp:TextBox ID="txtpwd" runat="server"></asp:TextBox></td></tr>
     <tr><td></td><td>
         <asp:Button ID="btnsubmit" runat="server" Text="Submit" /></td></tr>
      <tr><td colspan="2">
          <asp:Label ID="lblresult" runat="server"></asp:Label></td></tr>
    </table>
    </fieldset>

Import the namespace:
C# code:
using System.Security.Cryptography;
using System.Text;

VB.net Code:
Imports System.Text
Imports System.Security.Cryptography


Convert text into MD5 hash
Create a method to convert the string into MD5 hash and call it on button click.
C# code:
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        lblresult.Text = ConvertPwdtoMD5(txtpwd.Text);
    }
    public static string ConvertPwdtoMD5(string strword)
    {
        MD5 md5 = MD5.Create();
        byte[] Bytes = Encoding.ASCII.GetBytes(strword);
        byte[] hash = md5.ComputeHash(Bytes);
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sBuilder.Append(hash[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }

VB.net Code:
Protected Sub btnsubmit_Click(sender As Object, e As System.EventArgs) Handles btnsubmit.Click
        lblresult.Text = ConvertPwdtoMD5(txtpwd.Text)
    End Sub
    Public Shared Function ConvertPwdtoMD5(strword As String) As String
        Dim md5 As MD5 = md5.Create()
        Dim Bytes As Byte() = Encoding.ASCII.GetBytes(strword)
        Dim hash As Byte() = md5.ComputeHash(Bytes)
        Dim sBuilder As New StringBuilder()
        For i As Integer = 0 To hash.Length - 1
            sBuilder.Append(hash(i).ToString("x2"))
        Next
        Return sBuilder.ToString()
    End Function


Post a Comment

0 Comments