...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package hmac
21
22 import (
23 "crypto/hmac"
24 "crypto/md5"
25 "crypto/sha1"
26 "crypto/sha256"
27 "crypto/sha512"
28 "fmt"
29 "hash"
30 )
31
32 const (
33 MD5 = "MD5"
34 SHA1 = "SHA1"
35 SHA224 = "SHA224"
36 SHA256 = "SHA256"
37 SHA384 = "SHA384"
38 SHA512 = "SHA512"
39 SHA512_224 = "SHA512_224"
40 SHA512_256 = "SHA512_256"
41 )
42
43
44
45
46
47 func Sign(hashName string, key []byte, data []byte) ([]byte, error) {
48 hash, err := hashFromName(hashName)
49 if err != nil {
50 return nil, err
51 }
52 mac := hmac.New(hash, key)
53 mac.Write(data)
54 return mac.Sum(nil), nil
55 }
56
57 func hashFromName(hash string) (func() hash.Hash, error) {
58 switch hash {
59 case MD5:
60 return md5.New, nil
61 case SHA1:
62 return sha1.New, nil
63 case SHA224:
64 return sha256.New224, nil
65 case SHA256:
66 return sha256.New, nil
67 case SHA384:
68 return sha512.New384, nil
69 case SHA512:
70 return sha512.New, nil
71 case SHA512_224:
72 return sha512.New512_224, nil
73 case SHA512_256:
74 return sha512.New512_256, nil
75 }
76 return nil, fmt.Errorf("unsupported hash function")
77 }
78
View as plain text