C#, Microsoft Windows

Calculate a MD5 hash from a string in C#

Let’s see a simple function to calculate MD5 hashes of strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
public String MD5(String plaintext)
{
	MD5 md5 = System.Security.Cryptography.MD5.Create();
	byte[] bytes = System.Text.Encoding.ASCII.GetBytes(plaintext);
	byte[] hash = md5.ComputeHash(bytes);
 
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < hash.Length; i++)
	{
	    sb.Append(hash[i].ToString("x2"));
	}
	return sb.ToString();
}

Example:

String hash = MD5("salt1"+"GeorgeKarpouzas2012"+"salt2");