/
bytes_hash.go
35 lines (27 loc) · 1.22 KB
/
bytes_hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package g
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
)
// A struct that wraps an Bytes for hashing.
type bhash struct{ bytes Bytes }
// Hash returns a bhash struct wrapping the given Bytes.
func (bs Bytes) Hash() bhash { return bhash{bs} }
// MD5 computes the MD5 hash of the wrapped Bytes and returns the hash as an Bytes.
func (bh bhash) MD5() Bytes { return bytesHasher(md5.New(), bh.bytes) }
// SHA1 computes the SHA1 hash of the wrapped Bytes and returns the hash as an Bytes.
func (bh bhash) SHA1() Bytes { return bytesHasher(sha1.New(), bh.bytes) }
// SHA256 computes the SHA256 hash of the wrapped Bytes and returns the hash as an Bytes.
func (bh bhash) SHA256() Bytes { return bytesHasher(sha256.New(), bh.bytes) }
// SHA512 computes the SHA512 hash of the wrapped Bytes and returns the hash as an Bytes.
func (bh bhash) SHA512() Bytes { return bytesHasher(sha512.New(), bh.bytes) }
// bytesHasher a helper function that computes the hash of the given Bytes using the specified
// hash.Hash algorithm and returns the hash as an Bytes.
func bytesHasher(algorithm hash.Hash, bs Bytes) Bytes {
_, _ = algorithm.Write(bs)
return Bytes(hex.EncodeToString(algorithm.Sum(nil)))
}