C# Create A MD5 Hash From A String
This example shows how to create a MD5 hash from a string.
Usage:
string hash = CreateMD5Hash("http://www.csharpexamples.com");
Console.WriteLine(hash);
//Output:
//E426A83F137FA324C3412B92193EED1F
public string CreateMD5Hash(string input)
{
// Step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
Good one
You should use UTF8 not ASCII for the input normalization as well as normalizing the input string for consistent hashing of strings with special/joint characters…
Encoding.UTF8.GetBytes(input.Normalize(NormalizationForm.FormKC))