-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathalgorithm.go
32 lines (27 loc) · 928 Bytes
/
algorithm.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
package itsdangerous
import (
"crypto/hmac"
"crypto/subtle"
"hash"
)
// SigningAlgorithm provides interfaces to generate and verify signature
type SigningAlgorithm interface {
GetSignature(key, value string) []byte
VerifySignature(key, value string, sig []byte) bool
}
// HMACAlgorithm provides signature generation using HMACs.
type HMACAlgorithm struct {
DigestMethod func() hash.Hash
}
// GetSignature returns the signature for the given key and value.
func (a *HMACAlgorithm) GetSignature(key, value string) []byte {
a.DigestMethod().Reset()
h := hmac.New(func() hash.Hash { return a.DigestMethod() }, []byte(key))
h.Write([]byte(value))
return h.Sum(nil)
}
// VerifySignature verifies the given signature matches the expected signature.
func (a *HMACAlgorithm) VerifySignature(key, value string, sig []byte) bool {
eq := subtle.ConstantTimeCompare(sig, []byte(a.GetSignature(key, value)))
return eq == 1
}