-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
50 lines (40 loc) · 1.1 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
package encryption
import (
"encoding/hex"
"github.com/0chain/common/core/common"
"golang.org/x/crypto/sha3"
)
// ErrInvalidHash - hash is invalid error
var ErrInvalidHash = common.NewError("invalid_hash", "Invalid hash")
const HASH_LENGTH = 32
type HashBytes [HASH_LENGTH]byte
/*Hash - hash the given data and return the hash as hex string */
func Hash(data interface{}) string {
return hex.EncodeToString(RawHash(data))
}
func IsHash(str string) bool {
bytes, err := hex.DecodeString(str)
return err == nil && len(bytes) == HASH_LENGTH
}
// EmptyHash - hash of an empty string
var EmptyHash = Hash("")
// EmptyHashBytes - hash bytes of an empty string
var EmptyHashBytes = RawHash("")
/*RawHash - Logic to hash the text and return the hash bytes */
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)
buf := make([]byte, 0, hash.Size())
return hash.Sum(buf)
}