How to hash a string using SHA-256 in Go?

To hash a string using SHA-256 in Go, you can use the crypto/sha256 package. Here is an example code snippet that demonstrates how to accomplish this:

package main import ( "crypto/sha256" "encoding/hex" "fmt" ) func main() { str := "Hello, World!" // the string to be hashed // Create a new SHA256 hash hash := sha256.New() // Write the string to the hash hash.Write([]byte(str)) // Get the finalized hash result as a byte slice hashBytes := hash.Sum(nil) // Convert the byte slice to a hexadecimal string hashString := hex.EncodeToString(hashBytes) // Print the SHA256 hash fmt.Println(hashString) }

This code:

  1. Imports necessary packages (crypto/sha256, encoding/hex, and fmt).
  2. Defines the string to be hashed ("Hello, World!").
  3. Creates a new SHA256 hash using sha256.New().
  4. Writes the string to be hashed to the hash using hash.Write([]byte(str)).
  5. Gets the finalized hash result as a byte slice using hash.Sum(nil).
  6. Converts the byte slice to a hexadecimal string using hex.EncodeToString(hashBytes).
  7. Prints the resulting SHA256 hash using fmt.Println(hashString).

When you run this code, it will output the SHA256 hash of the string "Hello, World!".