This is a quick example of how to generate an MD5 hash from a string in C# and output it as a string. Converting a string to a byte array and back again is the only challenging part. I therefore need two methods: the first takes the byte array directly and returns a byte array, while the second converts the string to byte array and back again.
using System.Security.Cryptography;
public static string GetMD5(string text)
{
if (text == null)
{
return string.Empty;
}
byte[] message = System.Text.Encoding.ASCII.GetBytes(text);
byte[] hashValue = GetMD5(message);
string hashString = string.Empty;
foreach (byte x in hashValue)
{
hashString += string.Format("{0:x2}", x);
}
return hashString;
}
private static byte[] GetMD5(byte[] message)
{
MD5 hashString = new MD5CryptoServiceProvider();
return hashString.ComputeHash(message);
}
Leave a Reply