go-crypt/crypt/checksum.go
Claude 7407b89b8d
refactor(ax): AX RFC-025 compliance sweep pass 1
Remove banned imports (fmt, strings, os, errors, path/filepath) across all
production and test files, replace with core.* primitives, coreio.ReadStream,
and coreerr.E. Upgrade dappco.re/go/core v0.5.0 → v0.7.0 for core.PathBase
and core.Is. Fix isRepoScoped to exclude pr.* capabilities (enforcement is at
the forge layer, not the policy engine). Add Good/Bad/Ugly test coverage to
all packages missing the mandatory three-category naming convention.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-31 08:48:56 +01:00

63 lines
1.7 KiB
Go

package crypt
import (
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
goio "io"
coreio "dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
)
// SHA256File computes the SHA-256 checksum of a file and returns it as a hex string.
//
// sum, err := crypt.SHA256File("/path/to/archive.tar.gz")
func SHA256File(path string) (string, error) {
reader, err := coreio.ReadStream(coreio.Local, path)
if err != nil {
return "", coreerr.E("crypt.SHA256File", "failed to open file", err)
}
defer func() { _ = reader.Close() }()
h := sha256.New()
if _, err := goio.Copy(h, reader); err != nil {
return "", coreerr.E("crypt.SHA256File", "failed to read file", err)
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// SHA512File computes the SHA-512 checksum of a file and returns it as a hex string.
//
// sum, err := crypt.SHA512File("/path/to/archive.tar.gz")
func SHA512File(path string) (string, error) {
reader, err := coreio.ReadStream(coreio.Local, path)
if err != nil {
return "", coreerr.E("crypt.SHA512File", "failed to open file", err)
}
defer func() { _ = reader.Close() }()
h := sha512.New()
if _, err := goio.Copy(h, reader); err != nil {
return "", coreerr.E("crypt.SHA512File", "failed to read file", err)
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// SHA256Sum computes the SHA-256 checksum of data and returns it as a hex string.
//
// digest := crypt.SHA256Sum([]byte("hello")) // "2cf24dba..."
func SHA256Sum(data []byte) string {
h := sha256.Sum256(data)
return hex.EncodeToString(h[:])
}
// SHA512Sum computes the SHA-512 checksum of data and returns it as a hex string.
//
// digest := crypt.SHA512Sum([]byte("hello")) // "9b71d224..."
func SHA512Sum(data []byte) string {
h := sha512.Sum512(data)
return hex.EncodeToString(h[:])
}