-
Notifications
You must be signed in to change notification settings - Fork 26
/
hash.go
45 lines (39 loc) · 839 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
package crypto
import (
"encoding/hex"
"golang.org/x/crypto/sha3"
)
const HashLength = 32
type HashBytes [HashLength]byte
// Hash computes hash of the given data using RawHash and returns result as hex decoded string.
func Hash(data interface{}) string {
return hex.EncodeToString(RawHash(data))
}
// RawHash computes SHA3-256 hash depending on data type and returns the hash bytes.
//
// RawHash panics if data type is unknown.
//
// Known types:
//
// - []byte
//
// - HashBytes
//
// - string
func RawHash(data interface{}) []byte {
var databuf []byte
switch dataImpl := data.(type) {
case []byte:
databuf = dataImpl
case HashBytes:
databuf = dataImpl[:]
case string:
databuf = []byte(dataImpl)
default:
panic("unknown type")
}
hash := sha3.New256()
hash.Write(databuf)
var buf []byte
return hash.Sum(buf)
}