Skip to content

Commit

Permalink
hmac sign should accept a key as string
Browse files Browse the repository at this point in the history
  • Loading branch information
Dillon Streator authored and Dillon Streator committed Oct 12, 2022
1 parent 0c4e387 commit b96a661
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions hmac.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ func (m *SigningMethodHMAC) Alg() string {
// Verify implements token verification for the SigningMethod. Returns nil if the signature is valid.
func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
// Verify the key is the right type
keyBytes, ok := key.([]byte)
if !ok {
return ErrInvalidKeyType
keyBytes, err := m.keyBytesFrom(key)
if err != nil {
return err
}

// Decode signature, for comparison
Expand Down Expand Up @@ -80,16 +80,28 @@ func (m *SigningMethodHMAC) Verify(signingString, signature string, key interfac
// Sign implements token signing for the SigningMethod.
// Key must be []byte
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))
keyBytes, err := m.keyBytesFrom(key)
if err != nil {
return "", err
}

return EncodeSegment(hasher.Sum(nil)), nil
if !m.Hash.Available() {
return "", ErrHashUnavailable
}

return "", ErrInvalidKeyType
hasher := hmac.New(m.Hash.New, keyBytes)
hasher.Write([]byte(signingString))

return EncodeSegment(hasher.Sum(nil)), nil
}

func (m *SigningMethodHMAC) keyBytesFrom(value interface{}) ([]byte, error) {
switch v := value.(type) {
case []byte:
return v, nil
case string:
return []byte(v), nil
default:
return nil, ErrInvalidKeyType
}
}

0 comments on commit b96a661

Please sign in to comment.