-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
executable file
·83 lines (71 loc) · 1.74 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package ghash
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"github.com/davidforest123/goutil/basic/gerrors"
"hash"
)
type HashType string
const (
HashTypeSHA1 HashType = "sha1"
HashTypeSHA256 HashType = "sha256"
HashTypeSHA512 HashType = "sha512"
HashTypeSHA512_384 HashType = "sha512_384"
HashTypeMD5 HashType = "md5"
)
// GetSHA256 returns a SHA256 hash of a byte array
func GetSHA256(message []byte) []byte {
digest := sha256.New()
digest.Write(message)
return digest.Sum(nil)
}
// GetSHA512 returns a SHA512 hash of a byte array
func GetSHA512(message []byte) []byte {
sha := sha512.New()
sha.Write(message)
return sha.Sum(nil)
}
func GetSHA1(message []byte) []byte {
digest := sha1.New()
digest.Write(message)
return digest.Sum(nil)
}
// GetMD5 returns a MD5 hash of a byte array
func GetMD5(message []byte) []byte {
digest := md5.New()
digest.Write(message)
return digest.Sum(nil)
}
func GetHex(message []byte) string {
return hex.EncodeToString(message)
}
// HexEncodeToString takes in a hexadecimal byte array and returns a string
func HexEncodeToString(message []byte) string {
return hex.EncodeToString(message)
}
// GetHMAC returns a keyed-hash message authentication code using the desired
// hashtype
func GetHMAC(hashType HashType, plain, secret []byte) []byte {
var hash func() hash.Hash
switch hashType {
case HashTypeSHA1:
hash = sha1.New
case HashTypeSHA256:
hash = sha256.New
case HashTypeSHA512:
hash = sha512.New
case HashTypeSHA512_384:
hash = sha512.New384
case HashTypeMD5:
hash = md5.New
default:
panic(gerrors.New("unsupported hash type %s", hashType))
}
mac := hmac.New(hash, secret)
mac.Write(plain)
return mac.Sum(nil)
}