Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

MD5 Hashing using C#

Its common now a days that all the passwords are being encrypted in order to prevent data theft. So the passwords are being encrypted, the most common and most secure encryption method is MD5 hashing.
MD5 hashing stands for Message Digest algorithm 5. The idea of MD5 algorithm is to convert all the string/char/integer into a fixed “32″ bit hexadecimal code. The input can be of any size, but the output will always be fixed, here is an example of MD5 hashing algorithm.

MD5 hashing algorithm

The main point is that whatever the length of the input is, the output will always be of “32″ bit. The namespace used is System.Security.Cryptography and the assembly used is mscorlib (in mscorlib.dll).
The first step in creating a MD5 encryption using C# is :-

Step 1 : Include the required namespace.

using System.Security.Cryptography;
using System.Text;// for stringbuilder class

Step 2 : Create an object of MD5 class.

MD5 md5H=MD5.Create();

Step 3 : Convert the string into byte array and compute its hash.

byte[]data=md5H.ComputeHash(Encoding.UTF8.GetBytes(text));

Step 4 : Loop through each byte of hashed data and format each one as a hexadecimal string

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

The whole combined C# coding is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
 public partial class MD5Hashing:System.Web.UI.Page
 {
      public string MD5Hash(string text)
     {
         MD5 md5H=MD5.Create();
         //convert the input string to a byte array and compute its hash
         byte[]data=md5H.ComputeHash(Encoding.UTF8.GetBytes(text));
         // create a new stringbuilder to collect the bytes and create a string
         StringBuilder sB=new StringBuilder();
         //loop through each byte of hashed data and format each one as a hexadecimal string
         for(int i=0;i<data.Length;i++){
             sB.Append(data[i].ToString("x2"));
         }
         //return hexadecimal string
         return sB.ToString();
     }
 }

MD5 hashing output

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy