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:
crypto/sha256
, encoding/hex
, and fmt
)."Hello, World!"
).sha256.New()
.hash.Write([]byte(str))
.hash.Sum(nil)
.hex.EncodeToString(hashBytes)
.fmt.Println(hashString)
.When you run this code, it will output the SHA256 hash of the string "Hello, World!"
.