Files
util/sha256file.go
clawbot 62f769ae9b add SHA256File for checksumming a file
SHA256File returns the SHA-256 digest of a file's contents as lowercase
hexadecimal, copying the file through the hash in chunks so its size does not
matter. Comes with a doc comment and table-driven tests. (closes #19)

Model: opus-5
2026-09-05 03:32:00 +00:00

31 lines
777 B
Go

package util
import (
"crypto/sha256"
"encoding/hex"
"io"
"os"
)
// SHA256File returns the SHA-256 digest of the contents of the file at path,
// written as lowercase hexadecimal, in the same form as the sha256sum command
// prints. The file is copied through the hash in chunks rather than read into
// memory, so its size does not matter.
//
// The error is whatever went wrong opening or reading the file, passed along
// unchanged so a caller can test it with os.IsNotExist and the like.
func SHA256File(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
digest := sha256.New()
if _, err := io.Copy(digest, file); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}