github.com/TBD54566975/ftl@v0.219.0/internal/sha256/sha256.go (about)

     1  package sha256
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"encoding/hex"
     6  	"io"
     7  	"os"
     8  	"strconv"
     9  )
    10  
    11  // SHA256 is a type-safe wrapper around a SHA256 hash.
    12  type SHA256 [sha256.Size]byte
    13  
    14  // Sum "data" and return the SHA256 hash.
    15  func Sum(data []byte) SHA256 { return sha256.Sum256(data) }
    16  
    17  // SumReader "r" and return the SHA256 hash.
    18  func SumReader(r io.Reader) (SHA256, error) {
    19  	h := sha256.New()
    20  	_, err := io.Copy(h, r)
    21  	var out SHA256
    22  	copy(out[:], h.Sum(nil))
    23  	return out, err
    24  }
    25  
    26  func SumFile(path string) (SHA256, error) {
    27  	f, err := os.Open(path)
    28  	if err != nil {
    29  		return SHA256{}, err
    30  	}
    31  	defer f.Close() //nolint:gosec
    32  	return SumReader(f)
    33  }
    34  
    35  // FromBytes converts a SHA256 in []byte form to a SHA256.
    36  func FromBytes(data []byte) SHA256 {
    37  	var out SHA256
    38  	copy(out[:], data)
    39  	return out
    40  }
    41  
    42  // ParseSHA256 parses a hex-ecndoded SHA256 hash from a string.
    43  func ParseSHA256(s string) (SHA256, error) {
    44  	var out SHA256
    45  	err := out.UnmarshalText([]byte(s))
    46  	return out, err
    47  }
    48  
    49  // MustParseSHA256 parses a hex-ecndoded SHA256 hash from a string, panicing on error.
    50  func MustParseSHA256(s string) SHA256 {
    51  	out, err := ParseSHA256(s)
    52  	if err != nil {
    53  		panic(err)
    54  	}
    55  	return out
    56  }
    57  
    58  func (s *SHA256) UnmarshalText(text []byte) error {
    59  	_, err := hex.Decode(s[:], text)
    60  	return err
    61  }
    62  func (s SHA256) MarshalText() ([]byte, error) { return []byte(hex.EncodeToString(s[:])), nil }
    63  func (s SHA256) String() string               { return hex.EncodeToString(s[:]) }
    64  func (s SHA256) GoString() string             { return strconv.Quote(hex.EncodeToString(s[:])) }