github.com/storacha/go-ucanto@v0.7.2/core/ipld/hash/sha256/sha256.go (about)

     1  package sha256
     2  
     3  import (
     4  	"crypto/sha256"
     5  
     6  	"github.com/multiformats/go-multihash"
     7  	"github.com/storacha/go-ucanto/core/ipld/hash"
     8  )
     9  
    10  // sha2-256
    11  const Code = 0x12
    12  
    13  // sha2-256 hash has a 32-byte sum
    14  const Size = sha256.Size
    15  
    16  type hasher struct{}
    17  
    18  func (hasher) Code() uint64 {
    19  	return Code
    20  }
    21  
    22  func (hasher) Size() uint64 {
    23  	return Size
    24  }
    25  
    26  func (hasher) Sum(b []byte) (hash.Digest, error) {
    27  	s256h := sha256.New()
    28  	_, err := s256h.Write(b)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	sum := s256h.Sum(nil)
    33  
    34  	d, _ := multihash.Encode(sum, Code)
    35  	return hash.NewDigest(Code, Size, sum, d), nil
    36  }
    37  
    38  var Hasher = hasher{}