create a md5 hash from a string in csharp

To create an MD5 hash from a string in C#, you can use the System.Security.Cryptography namespace. Here's an example:

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

public static string GetMd5Hash(string input)
{
    using (var 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();
    }
}
470 chars
19 lines

To use the method, simply call it with a string input, like this:

main.cs
string input = "hello world";
string hash = GetMd5Hash(input);
Console.WriteLine(hash); // Output: 5eb63bbbe01eeed093cb22bb8f5acdc3
132 chars
4 lines

Note that in this example, the input string is converted to a byte array using UTF-8 encoding, and then the MD5.ComputeHash method is used to compute the hash. Finally, the hash bytes are converted to a hexadecimal string representation and returned.

gistlibby LogSnag