The MD5 (message-digest algorithm) in used in a wide variety of cryptographic applications, and is commonly used to verify data integrity.
The following code will show you how to create a simple utility class that converts strings into MD5 hashes, and an example of its usage by creating a Gravatar image link.
The HashUtil class
public class HashUtil
{
public static string CreateMD5(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentNullException("input");
}
using (var md5 = MD5.Create())
{
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// convert byte array to hex string
var sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
}
Example usage
The following example creates an MD5 hash of an email address and then builds a Gravatar URL.
string hash = HashUtil.CreateMD5("[email protected]");
string url = String.Format("//www.gravatar.com/avatar/{0}?d=mm", hash);