create a blake2s hash from a string in go

To create a blake2s hash from a string in go, we need to follow these steps:

  1. Import the necessary packages: "crypto/blake2s" and "encoding/hex".
  2. Convert the string to a byte slice.
  3. Create a new blake2s hash with blake2s.New256().
  4. Write the byte slice to the hash with hash.Write([]byte).
  5. Finalize the hash with hash.Sum(nil).
  6. Encode the finalized hash as hex with hex.EncodeToString([]byte).

Here's the code:

main.go
import (
    "crypto/blake2s"
    "encoding/hex"
)

func createBlake2sHash(s string) (string, error) {
    // Convert string to byte slice
    bytes := []byte(s)

    // Create new blake2s hash
    hash := blake2s.New256()

    // Write byte slice to hash
    hash.Write(bytes)

    // Finalize hash and convert to hex
    finalHash := hash.Sum(nil)
    finalHashHex := hex.EncodeToString(finalHash)

    return finalHashHex, nil
}
432 chars
22 lines

To use this function, simply call createBlake2sHash with the string you want to hash. It will return the blake2s hash as a hex-encoded string.

gistlibby LogSnag