|
| 1 | +// Package hasher provides types and interfaces for hash calculating. |
| 2 | +package hasher |
| 3 | + |
| 4 | +import ( |
| 5 | + "crypto/sha1" //nolint:gosec |
| 6 | + "crypto/sha256" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "hash" |
| 10 | +) |
| 11 | + |
| 12 | +// ErrDataIsNil is returned if the passed data is nil. |
| 13 | +var ErrDataIsNil = errors.New("data is nil") |
| 14 | + |
| 15 | +// Hasher is the interface that storage hashers must implement. |
| 16 | +// It provides low-level operations for hash calculating. |
| 17 | +type Hasher interface { |
| 18 | + Name() string |
| 19 | + Hash(data []byte) ([]byte, error) |
| 20 | +} |
| 21 | + |
| 22 | +type sha256Hasher struct { |
| 23 | + hash hash.Hash |
| 24 | +} |
| 25 | + |
| 26 | +// NewSHA256Hasher creates a new sha256Hasher instance. |
| 27 | +func NewSHA256Hasher() Hasher { |
| 28 | + return &sha256Hasher{ |
| 29 | + hash: sha256.New(), |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Name implements Hasher interface. |
| 34 | +func (h *sha256Hasher) Name() string { |
| 35 | + return "sha256" |
| 36 | +} |
| 37 | + |
| 38 | +// Hash implements Hasher interface. |
| 39 | +func (h *sha256Hasher) Hash(data []byte) ([]byte, error) { |
| 40 | + if data == nil { |
| 41 | + return nil, ErrDataIsNil |
| 42 | + } |
| 43 | + |
| 44 | + n, err := h.hash.Write(data) |
| 45 | + if n < len(data) || err != nil { |
| 46 | + return nil, fmt.Errorf("failed to write data: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + return h.hash.Sum(nil), nil |
| 50 | +} |
| 51 | + |
| 52 | +type sha1Hasher struct { |
| 53 | + hash hash.Hash |
| 54 | +} |
| 55 | + |
| 56 | +// NewSHA1Hasher creates a new NewSHA1Hasher instance. |
| 57 | +func NewSHA1Hasher() Hasher { |
| 58 | + return &sha1Hasher{ |
| 59 | + hash: sha1.New(), //nolint:gosec |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// Name implements Hasher interface. |
| 64 | +func (h *sha1Hasher) Name() string { |
| 65 | + return "sha1" |
| 66 | +} |
| 67 | + |
| 68 | +// Hash implements Hasher interface. |
| 69 | +func (h *sha1Hasher) Hash(data []byte) ([]byte, error) { |
| 70 | + if data == nil { |
| 71 | + return nil, ErrDataIsNil |
| 72 | + } |
| 73 | + |
| 74 | + n, err := h.hash.Write(data) |
| 75 | + if n < len(data) || err != nil { |
| 76 | + return nil, fmt.Errorf("failed to write data: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + return h.hash.Sum(nil), nil |
| 80 | +} |
0 commit comments