-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhmac.go
75 lines (61 loc) · 1.62 KB
/
hmac.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package jwt
import (
"bytes"
"crypto"
"crypto/hmac"
"errors"
)
// Implements the HMAC-Streebog family of signing methods signing methods
type SigningMethodHMAC struct {
Name string
Hash crypto.Hash
}
// Specific instances for HG256 and company
var (
SigningMethodHG256 *SigningMethodHMAC
SigningMethodHG512 *SigningMethodHMAC
)
func init() {
// HG256
SigningMethodHG256 = &SigningMethodHMAC{"HG256", crypto.GOSTR34112012256}
RegisterSigningMethod(SigningMethodHG256.Alg(), func() SigningMethod {
return SigningMethodHG256
})
// HG512
SigningMethodHG512 = &SigningMethodHMAC{"HG512", crypto.GOSTR34112012512}
RegisterSigningMethod(SigningMethodHG512.Alg(), func() SigningMethod {
return SigningMethodHG512
})
}
func (m *SigningMethodHMAC) Alg() string {
return m.Name
}
func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
if keyBytes, ok := key.([]byte); ok {
var sig []byte
var err error
if sig, err = DecodeSegment(signature); err == nil {
if !m.Hash.Available() {
return ErrHashUnavailable
}
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
if !bytes.Equal(sig, hasher.Sum(nil)) {
err = errors.New("signature is invalid")
}
}
return err
}
return ErrInvalidKey
}
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
if keyBytes, ok := key.([]byte); ok {
if !m.Hash.Available() {
return "", ErrHashUnavailable
}
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))
return EncodeSegment(hasher.Sum(nil)), nil
}
return "", ErrInvalidKey
}