Go by Example: SHA256 Hashes

Go provides a hash package that implements various hash algorithms, including SHA256. Here’s an example of how you can use the sha256 package to compute the SHA256 hash of a string:

package main

import (
	"crypto/sha256"
	"fmt"
)

func main() {
	// Compute the SHA256 hash of a string
	s := "hello, world"
	h := sha256.Sum256([]byte(s))

	// Print the hash in hexadecimal
	fmt.Printf("%x\n", h)
}

In this example, the sha256.Sum256 function is used to compute the SHA256 hash of a string. The input to this function is a byte slice, so we first convert the string to a byte slice using the []byte conversion.

The result of the sha256.Sum256 function is a [32]byte array, which we then print in hexadecimal using the %x format specifier in a call to fmt.Printf.

The output of this program will be something like:

7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *