create a sha3_256 hash from a string in csharp

Here's how to create a SHA3_256 hash from a string in CSharp using the System.Security.Cryptography namespace:

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

// create a SHA3_256 hash from a string
public static string GetSha3_256Hash(string input)
{
    using (var sha3 = SHA3.Create())
    {
        // convert input string to byte array
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);

        // compute hash value as byte array
        byte[] hashBytes = sha3.ComputeHash(inputBytes);

        // convert byte array to string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }
        return sb.ToString();
    }
}
649 chars
24 lines

You can call this method and pass in any string to get its SHA3_256 hash value. Note that we're converting the input string to a byte array using Encoding.UTF8.GetBytes() before computing the hash, and then converting the hash value (which is also a byte array) to a string using a StringBuilder.

gistlibby LogSnag