Go

SHA-256 Hash of File or String

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`crypto/sha256` is the canonical hash. Use the streaming `Hash` interface for files — never load multi-GB content into memory just to hash it.
Go
Raw
package main

import (
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "io"
    "os"
)

// Hash a small in-memory value
func hashString(s string) string {
    sum := sha256.Sum256([]byte(s))
    return hex.EncodeToString(sum[:])
}

// Hash a file via streaming — constant memory
func hashFile(path string) (string, error) {
    f, err := os.Open(path)
    if err != nil { return "", err }
    defer f.Close()
    h := sha256.New()
    if _, err := io.Copy(h, f); err != nil { return "", err }
    return hex.EncodeToString(h.Sum(nil)), nil
}

func main() {
    fmt.Println(hashString("hello world"))           // b94d27b...

    if h, err := hashFile("Cargo.toml"); err == nil {
        fmt.Println(h)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.