Sha256 Hashes in C#

Here’s the translation of the SHA256 Hashes example from Go to C#:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in C#.

using System;
using System.Security.Cryptography;
using System.Text;

class SHA256Hashes
{
    static void Main()
    {
        string s = "sha256 this string";

        // Here we start with a new hash.
        using (SHA256 sha256Hash = SHA256.Create())
        {
            // ComputeHash expects bytes. If you have a string s,
            // use Encoding.UTF8.GetBytes(s) to convert it to bytes.
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(s));

            // Convert byte array to a string
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            string hash = builder.ToString();

            Console.WriteLine(s);
            Console.WriteLine(hash);
        }
    }
}

Running the program computes the hash and prints it in a human-readable hex format.

$ dotnet run
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you can use SHA512.Create() instead.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!