-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcrypto.go
More file actions
39 lines (32 loc) · 802 Bytes
/
crypto.go
File metadata and controls
39 lines (32 loc) · 802 Bytes
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
package aliyuniot
import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"hash"
)
const (
DefaultSignAlgorithm = HMACSHA1
HMACSHA1 = "sha1"
HMACSHA256 = "sha256"
)
func hmacSign(algo string, secret, data string) string {
hfun := buildHashFunc(algo)
// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(hfun, []byte(secret))
// Write Data to it
h.Write([]byte(data))
// Get result and encode as hexadecimal string
return hex.EncodeToString(h.Sum(nil))
}
type hashFunc func() hash.Hash
func buildHashFunc(algo string) hashFunc {
switch algo {
case HMACSHA256:
return sha256.New
case HMACSHA1:
return sha1.New
}
panic("unsupport hash algorithm:" + string(algo))
}