-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhmac.go
More file actions
43 lines (36 loc) · 986 Bytes
/
hmac.go
File metadata and controls
43 lines (36 loc) · 986 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
40
41
42
43
package jwt
import (
"crypto/hmac"
"crypto/sha256"
)
// SigningMethodHMAC implements HS256.
type SigningMethodHMAC struct {
Name string
}
var signingMethodHS256 = &SigningMethodHMAC{Name: "HS256"}
// SigningMethodHS256 is the HMAC-SHA256 signing method.
var SigningMethodHS256 SigningMethod = signingMethodHS256
func (m *SigningMethodHMAC) Alg() string {
return m.Name
}
func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error {
keyBytes, ok := key.([]byte)
if !ok {
return ErrInvalidKeyType
}
hasher := hmac.New(sha256.New, keyBytes)
hasher.Write([]byte(signingString))
if !hmac.Equal(sig, hasher.Sum(nil)) {
return ErrSignatureInvalid
}
return nil
}
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) {
keyBytes, ok := key.([]byte)
if !ok {
return nil, ErrInvalidKeyType
}
hasher := hmac.New(sha256.New, keyBytes)
hasher.Write([]byte(signingString))
return hasher.Sum(nil), nil
}