SHA256 Hashes in Go
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.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go