How to generate a MD5 hash from a string in C# and VB.NET

To generate a MD5 hash from a string in C# and VB.NET you can use the following snippet.

Sample C#

public static string GenerateMd5Hash(string input)
{
	var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
	var computeHash = System.Text.Encoding.UTF8.GetBytes(input);
	computeHash = x.ComputeHash(computeHash);
	var stringBuilder = new System.Text.StringBuilder();
	foreach (var byte in computeHash)
	{
		stringBuilder.Append(byte.ToString("x2").ToLower());
	}
	return stringBuilder.ToString();
}

Sample VB.NET

Public Shared Function GenerateMd5Hash(input As String) As String
	Dim x = New System.Security.Cryptography.MD5CryptoServiceProvider()
	Dim computeHash = System.Text.Encoding.UTF8.GetBytes(input)
	computeHash = x.ComputeHash(computeHash)
	Dim stringBuilder = New System.Text.StringBuilder()
	For Each byte As var In computeHash
		stringBuilder.Append(byte.ToString("x2").ToLower())
	Next
	Return stringBuilder.ToString()
End Function

One thought on “How to generate a MD5 hash from a string in C# and VB.NET

Leave a Reply