-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mac.go
49 lines (42 loc) · 824 Bytes
/
mac.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
package server
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"strings"
)
const MacPathPrefix = "/"
type MAC []byte
func ComputeMac(
clientId string,
path string,
clientSecret []byte,
) (MAC, error) {
path = strings.TrimLeft(path, MacPathPrefix)
mac := hmac.New(sha256.New, clientSecret)
items := [][]byte{
[]byte(clientId),
[]byte(MacPathPrefix),
[]byte(path),
}
for _, item := range items {
n, err := mac.Write(item)
if err != nil {
return nil, err
}
if n != len(item) {
return nil, errors.New("write did not write all bytes")
}
}
return mac.Sum(nil), nil
}
func UrlDecodeMAC(s string) (MAC, error) {
return UrlDecodeBytes(s)
}
func (mac MAC) UrlEncode() string {
return UrlEncodeBytes(mac)
}
func (mac MAC) String() string {
return hex.EncodeToString(mac)
}