Sha256 Hashes in Visual Basic .NET

Here’s the translation of the SHA256 hashes example from Go to Visual Basic .NET:

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 Visual Basic .NET.

Imports System
Imports System.Security.Cryptography
Imports System.Text

Module SHA256Hashes
    Sub Main()
        Dim s As String = "sha256 this string"

        ' Here we start with a new hash.
        Using sha256 As SHA256 = SHA256.Create()
            ' GetBytes expects a string. It converts the string to bytes.
            Dim inputBytes As Byte() = Encoding.UTF8.GetBytes(s)

            ' This computes the hash and returns it as a byte array.
            Dim hashBytes As Byte() = sha256.ComputeHash(inputBytes)

            ' Convert the byte array to a hexadecimal string.
            Dim hashString As String = BitConverter.ToString(hashBytes).Replace("-", "").ToLower()

            Console.WriteLine(s)
            Console.WriteLine(hashString)
        End Using
    End Sub
End Module

Visual Basic .NET implements several hash functions in the System.Security.Cryptography namespace.

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, use SHA512.Create() instead of SHA256.Create().

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