ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

ToMd5Hash

Convert a input string to a byte array and compute the hash.

Source

/// <summary>
/// Convert a input string to a byte array and compute the hash.
/// </summary>
/// <param name="value">Input string.</param>
/// <returns>Hexadecimal string.</returns>
public static string ToMd5Hash(this string value)
{
	if (string.IsNullOrEmpty(value))
	{
		return value;
	}

	using (MD5 md5 = new MD5CryptoServiceProvider())
	{
		byte[] originalBytes = ASCIIEncoding.Default.GetBytes(value);
		byte[] encodedBytes = md5.ComputeHash(originalBytes);
		return BitConverter.ToString(encodedBytes).Replace("-", string.Empty);
	}
}

Example

string value = "this is a string";
Console.WriteLine(value.ToMd5Hash());

Author: Alvaro Torres Tatis

Submitted on: 5 jun 2012

Language: C#

Type: System.String

Views: 6554