2012-07-07 02:02:02 +04:00
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2012-07-07 04:02:20 +04:00
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
2012-07-07 02:02:02 +04:00
|
|
|
"errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SigningMethodHS256 struct{}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
RegisterSigningMethod("HS256", func() SigningMethod {
|
|
|
|
return new(SigningMethodHS256)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2012-07-07 04:02:20 +04:00
|
|
|
func (m *SigningMethodHS256) Alg() string {
|
2012-07-07 02:43:17 +04:00
|
|
|
return "HS256"
|
|
|
|
}
|
|
|
|
|
2012-07-07 02:02:02 +04:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2012-07-07 04:02:20 +04:00
|
|
|
func (m *SigningMethodHS256) Sign(signingString string, key []byte) (string, error) {
|
2012-07-07 02:43:17 +04:00
|
|
|
hasher := hmac.New(sha256.New, key)
|
|
|
|
hasher.Write([]byte(signingString))
|
2012-07-07 04:02:20 +04:00
|
|
|
|
2012-07-07 02:43:17 +04:00
|
|
|
return EncodeSegment(hasher.Sum(nil)), nil
|
2012-07-07 02:02:02 +04:00
|
|
|
}
|