You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.1 KiB

  1. package tmhash
  2. import (
  3. "crypto/sha256"
  4. "hash"
  5. )
  6. const (
  7. Size = sha256.Size
  8. BlockSize = sha256.BlockSize
  9. )
  10. // New returns a new hash.Hash.
  11. func New() hash.Hash {
  12. return sha256.New()
  13. }
  14. // Sum returns the SHA256 of the bz.
  15. func Sum(bz []byte) []byte {
  16. h := sha256.Sum256(bz)
  17. return h[:]
  18. }
  19. //-------------------------------------------------------------
  20. const (
  21. TruncatedSize = 20
  22. )
  23. type sha256trunc struct {
  24. sha256 hash.Hash
  25. }
  26. func (h sha256trunc) Write(p []byte) (n int, err error) {
  27. return h.sha256.Write(p)
  28. }
  29. func (h sha256trunc) Sum(b []byte) []byte {
  30. shasum := h.sha256.Sum(b)
  31. return shasum[:TruncatedSize]
  32. }
  33. func (h sha256trunc) Reset() {
  34. h.sha256.Reset()
  35. }
  36. func (h sha256trunc) Size() int {
  37. return TruncatedSize
  38. }
  39. func (h sha256trunc) BlockSize() int {
  40. return h.sha256.BlockSize()
  41. }
  42. // NewTruncated returns a new hash.Hash.
  43. func NewTruncated() hash.Hash {
  44. return sha256trunc{
  45. sha256: sha256.New(),
  46. }
  47. }
  48. // SumTruncated returns the first 20 bytes of SHA256 of the bz.
  49. func SumTruncated(bz []byte) []byte {
  50. hash := sha256.Sum256(bz)
  51. return hash[:TruncatedSize]
  52. }