compute string md5 in csharp

To compute the MD5 hash value of a string in C#, you can use the MD5 class from the System.Security.Cryptography namespace.

First, convert the string to a byte array using Encoding.UTF8.GetBytes() method. Then call the ComputeHash() method of the MD5 class passing in the byte array.

Here's the code:

main.cs
using System.Security.Cryptography;
using System.Text;

public static string ComputeMD5Hash(string input)
{
    using (MD5 md5 = MD5.Create())
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        byte[] hashBytes = md5.ComputeHash(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }
        return sb.ToString();
    }
}
474 chars
19 lines

Example usage:

main.cs
string input = "Hello World!";
string md5Hash = ComputeMD5Hash(input);
Console.WriteLine(md5Hash);
99 chars
4 lines

This will output: ed076287532e86365e841e92bfc50d8c.

related categories

gistlibby LogSnag