can now pass a PublicKey to SigningMethodRSA.Verify

This commit is contained in:
Simon Jefford 2014-08-07 08:45:21 +01:00 committed by Dave Grijalva
parent dc2f34cdb1
commit 33523225e1
2 changed files with 33 additions and 11 deletions

29
rsa.go
View File

@ -44,6 +44,9 @@ func (m *SigningMethodRSA) Alg() string {
return m.Name return m.Name
} }
// Implements the Verify method from SigningMethod
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as
// []byte, or an rsa.PrivateKey structure.
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
var err error var err error
@ -53,21 +56,25 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
return err return err
} }
if keyBytes, ok := key.([]byte); ok { var rsaKey *rsa.PublicKey
var rsaKey *rsa.PublicKey
if rsaKey, err = m.parsePublicKey(keyBytes); err != nil { switch k := key.(type) {
case []byte:
if rsaKey, err = m.parsePublicKey(k); err != nil {
return err return err
} }
case *rsa.PublicKey:
// Create hasher rsaKey = k
hasher := m.Hash.New() default:
hasher.Write([]byte(signingString))
// Verify the signature
return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
} else {
return ErrInvalidKey return ErrInvalidKey
} }
// Create hasher
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
// Verify the signature
return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
} }
// Implements the Sign method from SigningMethod // Implements the Sign method from SigningMethod

View File

@ -78,6 +78,21 @@ func TestRSASign(t *testing.T) {
} }
} }
func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key.pub")
method := GetSigningMethod("RS256").(*SigningMethodRSA)
parsedKey, err := method.parsePublicKey(key)
if err != nil {
t.Fatal(err)
}
testData := rsaTestData[0]
parts := strings.Split(testData.tokenString, ".")
err = method.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
if err != nil {
t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
}
}
func TestRSAWithPreParsedPrivateKey(t *testing.T) { func TestRSAWithPreParsedPrivateKey(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key") key, _ := ioutil.ReadFile("test/sample_key")
method := GetSigningMethod("RS256").(*SigningMethodRSA) method := GetSigningMethod("RS256").(*SigningMethodRSA)