9
// Implements the HMAC-SHA family of signing methods signing methods
10
type SigningMethodHMAC struct {
15
// Specific instances for HS256 and company
17
SigningMethodHS256 *SigningMethodHMAC
18
SigningMethodHS384 *SigningMethodHMAC
19
SigningMethodHS512 *SigningMethodHMAC
20
ErrSignatureInvalid = errors.New("signature is invalid")
25
SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
26
RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
27
return SigningMethodHS256
31
SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
32
RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
33
return SigningMethodHS384
37
SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
38
RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
39
return SigningMethodHS512
43
func (m *SigningMethodHMAC) Alg() string {
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)
55
// Decode signature, for comparison
56
sig, err := DecodeSegment(signature)
61
// Can we use the specified hashing method?
62
if !m.Hash.Available() {
63
return ErrHashUnavailable
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
75
// No validation errors. Signature is good.
79
// Implements the Sign method from SigningMethod for this signing method.
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
87
hasher := hmac.New(m.Hash.New, keyBytes)
88
hasher.Write([]byte(signingString))
90
return EncodeSegment(hasher.Sum(nil)), nil
93
return "", ErrInvalidKey