SHA256 Hashes in Go
Golang Concepts
Go: SHA256 Hashes
Go's
crypto/sha256
package provides functionality for computing SHA256 hashes. SHA256 is a widely-used cryptographic hash function that produces a fixed-size 256-bit hash value from an arbitrary input.
How to compute the SHA256 hash of a string in Go
Here's an example of how to compute the SHA256 hash of a string:
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
str := "hello world"
hash := sha256.Sum256([]byte(str))
fmt.Printf("%x\n", hash)
}
In this example, the sha256.Sum256()
function is used to compute the SHA256 hash of the string hello world
. The function returns a fixed-size array of bytes representing the hash value. You can convert this byte array to a hexadecimal string using the %x
format specifier in fmt.Printf()
.
Here are some other functions you can use for computing SHA256 hashes in Go:
- func New() hash.Hash: creates a new SHA256 hash object that can be used to compute the hash incrementally.
- func (d *Digest) Reset(): resets the SHA256 hash to its initial state.
- func (d *Digest) Write(p []byte) (n int, err error): writes data to the SHA256 hash and returns the number of bytes written.
- func (d *Digest) Sum(in []byte) ([]byte): adds the current hash to in and returns the resulting slice.
Note that cryptographic hashes are one-way functions, which means it is computationally infeasible to recover the original input from the hash value.