-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsymmetric.go
More file actions
61 lines (48 loc) · 1.23 KB
/
symmetric.go
File metadata and controls
61 lines (48 loc) · 1.23 KB
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
package httpsig
import (
"crypto"
"crypto/hmac"
"crypto/subtle"
"fmt"
)
func newSymmetricSigner(key []byte, kid string, alg SignatureAlgorithm) (*symmetricSigner, error) {
var hash crypto.Hash
switch alg {
case HmacSha256:
hash = crypto.SHA256
case HmacSha384:
hash = crypto.SHA384
case HmacSha512:
hash = crypto.SHA512
default:
return nil, fmt.Errorf("%w: %s", ErrUnsupportedAlgorithm, alg)
}
return &symmetricSigner{
alg: alg,
key: key,
kid: kid,
hash: hash,
}, nil
}
type symmetricSigner struct {
alg SignatureAlgorithm
key []byte
kid string
hash crypto.Hash
}
func (ms *symmetricSigner) keyID() string { return ms.kid }
func (ms *symmetricSigner) algorithm() SignatureAlgorithm { return ms.alg }
func (ms *symmetricSigner) signPayload(data []byte) ([]byte, error) { return ms.hmac(data), nil }
func (ms *symmetricSigner) verifyPayload(data []byte, mac []byte) error {
if match := subtle.ConstantTimeCompare(mac, ms.hmac(data)); match != 1 {
return ErrInvalidSignature
}
return nil
}
func (ms *symmetricSigner) hmac(payload []byte) []byte {
hmac := hmac.New(ms.hash.New, ms.key)
// According to documentation, Write() on hash never fails
_, _ = hmac.Write(payload)
mac := hmac.Sum(nil)
return mac
}