forked from dgrijalva/jwt-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sha256.go
41 lines (33 loc) · 843 Bytes
/
sha256.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
package jwt
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"errors"
)
type SigningMethodHS256 struct{}
func init() {
RegisterSigningMethod("HS256", func() SigningMethod {
return new(SigningMethodHS256)
})
}
func (m *SigningMethodHS256) Alg() string {
return "HS256"
}
func (m *SigningMethodHS256) Verify(signingString, signature string, key []byte) (err error) {
// Key
var sig []byte
if sig, err = DecodeSegment(signature); err == nil {
hasher := hmac.New(sha256.New, key)
hasher.Write([]byte(signingString))
if !bytes.Equal(sig, hasher.Sum(nil)) {
err = errors.New("Signature is invalid")
}
}
return
}
func (m *SigningMethodHS256) Sign(signingString string, key []byte) (string, error) {
hasher := hmac.New(sha256.New, key)
hasher.Write([]byte(signingString))
return EncodeSegment(hasher.Sum(nil)), nil
}