Debian Codegraph @

vendor/github.com/dgrijalva/jwt-go/hmac.go

raw
1 package jwt
2
3 import (
4 "crypto"
5 "crypto/hmac"
6 "errors"
7 )
8
9 // Implements the HMAC-SHA family of signing methods signing methods
10 type SigningMethodHMAC struct {
11 Name string
12 Hash crypto.Hash
13 }
14
15 // Specific instances for HS256 and company
16 var (
17 SigningMethodHS256 *SigningMethodHMAC
18 SigningMethodHS384 *SigningMethodHMAC
19 SigningMethodHS512 *SigningMethodHMAC
20 ErrSignatureInvalid = errors.New("signature is invalid")
21 )
22
23 func init() {
24 // HS256
25 SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
26 RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
27 return SigningMethodHS256
28 })
29
30 // HS384
31 SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
32 RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
33 return SigningMethodHS384
34 })
35
36 // HS512
37 SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
38 RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
39 return SigningMethodHS512
40 })
41 }
42
43 func (m *SigningMethodHMAC) Alg() string {
44 return m.Name
45 }
46
47 // Verify the signature of HSXXX tokens. Returns nil if the signature is valid.
48 func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
49 // Verify the key is the right type
50 keyBytes, ok := key.([]byte)
51 if !ok {
52 return ErrInvalidKeyType
53 }
54
55 // Decode signature, for comparison
56 sig, err := DecodeSegment(signature)
57 if err != nil {
58 return err
59 }
60
61 // Can we use the specified hashing method?
62 if !m.Hash.Available() {
63 return ErrHashUnavailable
64 }
65
66 // This signing method is symmetric, so we validate the signature
67 // by reproducing the signature from the signing string and key, then
68 // comparing that against the provided signature.
69 hasher := hmac.New(m.Hash.New, keyBytes)
70 hasher.Write([]byte(signingString))
71 if !hmac.Equal(sig, hasher.Sum(nil)) {
72 return ErrSignatureInvalid
73 }
74
75 // No validation errors. Signature is good.
76 return nil
77 }
78
79 // Implements the Sign method from SigningMethod for this signing method.
80 // Key must be []byte
81 func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
82 if keyBytes, ok := key.([]byte); ok {
83 if !m.Hash.Available() {
84 return "", ErrHashUnavailable
85 }
86
87 hasher := hmac.New(m.Hash.New, keyBytes)
88 hasher.Write([]byte(signingString))
89
90 return EncodeSegment(hasher.Sum(nil)), nil
91 }
92
93 return "", ErrInvalidKey
94 }