-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhash.go
60 lines (53 loc) · 1.45 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package aghash
import (
"crypto/md5" // #nosec
"encoding/base64"
"encoding/hex"
"github.com/davecgh/go-spew/spew"
"github.com/pkg/errors"
)
// Hash computes a hash of the provided object
func Hash(i interface{}) ([]byte, error) {
h := md5.New() // #nosec
printer := spew.ConfigState{
Indent: " ",
SortKeys: true,
DisableMethods: true,
SpewKeys: true,
}
_, err := printer.Fprintf(h, "%#v", i)
return h.Sum(nil), errors.Wrap(err, "can't take hash")
}
// HashSet computes a hash of the provided set of objects.
// Hash will have the same value regardless of objects order.
func HashSet(elems ...interface{}) ([]byte, error) {
result := make([]byte, md5.Size)
for _, elem := range elems {
h, err := Hash(elem)
if err != nil {
return result, err
}
for i := range result {
result[i] = result[i] ^ h[i]
}
}
return result, nil
}
// HashBase64 computes a string hash of the provided object
func HashBase64(i interface{}) (string, error) {
bs, err := Hash(i)
return base64.StdEncoding.EncodeToString(bs), err
}
// HashSetBase64 computes a string hash of the provided set of objects
func HashSetBase64(elems ...interface{}) (string, error) {
bs, err := HashSet(elems...)
return base64.StdEncoding.EncodeToString(bs), err
}
// HashHex takes a hash and encodes hash into hex
func HashHex(content []byte) (string, error) {
hash, err := Hash(content)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}