Friday, April 24, 2009

How to Generate MD5 hash of a string In C#.

How to Generate MD5 hash of a string In C#.
we can genetrate Hash of string in C# using various hashing algorithms.
method to generate hashed string is same for all algorithm.
.Net have many hashing algorithms like for Computing hash string.
eg. MD5 ,SHA1 etc.

(1)Create object of particular algorithm.
(2)Call ComputeHash method on your data.

method ComputeHash Takes Byte array as argument so we will Convert input data in byte array and that pass it to Compute Hash.we will use Encoding namespace to convert data in byte array.
we have to include namespaces.

(1)using System.Security.Cryptography;
(2)using System.Text;

here is the method to Generate Hashed String for UserData.this method will take string as input and returns hashed string.



public static string GetMD5HasCode(string UserData)
{
string HashedOutPut = string.Empty;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(UserData));
for (int i = 0; i < hashedBytes.Length; i++)
{
HashedOutPut += hashedBytes[i].ToString("x2").ToLower();
}
return HashedOutPut;
}


above function will return String of input string in Hexadecimal.
we can Use different format modifire to change output in various formats available.
ex.

F=Real Numbers
X=Hexadecimal
C=Currency

Thanks.