create a sha256 hash from a string in go

Here's an example of how to create a SHA256 hash from a string in Go:

main.go
package main

import (
    "crypto/sha256"
    "fmt"
)

func main() {
    // String to be hashed
    str := "Hello, world!"
    
    // Create a new SHA256 hash object
    h := sha256.New()
    
    // Write the string to the hash object
    h.Write([]byte(str))
    
    // Calculate the hash sum
    sum := h.Sum(nil)
    
    // Print the hash in hexadecimal format
    fmt.Printf("%x\n", sum)
}
399 chars
24 lines

In this example, we first import the crypto/sha256 package to access the SHA256 hash algorithm. We then create a new SHA256 hash object using the sha256.New() function.

We write our string to the hash object using the h.Write([]byte(str)) method. This method expects a byte slice, so we convert our string to a byte slice using the []byte() type conversion.

We then calculate the hash sum using the h.Sum(nil) method. This returns a byte slice containing the hash sum.

Lastly, we print the hash sum in hexadecimal format using %x format specifier and Printf() method.

gistlibby LogSnag