-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
52 lines (43 loc) · 934 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Author: fasion
* Created time: 2023-01-12 15:04:53
* Last Modified by: fasion
* Last Modified time: 2023-01-12 15:10:31
*/
package baseutils
import (
"crypto"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"hash"
)
var hasherCreators = map[crypto.Hash]func() hash.Hash{
crypto.MD5: md5.New,
crypto.SHA1: sha1.New,
crypto.SHA224: sha256.New224,
crypto.SHA256: sha256.New,
crypto.SHA512: sha512.New,
}
func NewHash(hash crypto.Hash) (hash.Hash, error) {
creator, ok := hasherCreators[hash]
if !ok {
return nil, nil
}
return creator(), nil
}
func HashData(hash crypto.Hash, datas ...[]byte) ([]byte, error) {
hasher, err := NewHash(hash)
if err != nil {
return nil, err
}
for _, data := range datas {
hasher.Write(data)
}
return hasher.Sum(nil), nil
}
func HashDataSilently(hash crypto.Hash, datas ...[]byte) []byte {
hashed, _ := HashData(hash, datas...)
return hashed
}