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

17
rsa.go
View File

@ -44,6 +44,9 @@ func (m *SigningMethodRSA) Alg() string {
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 {
var err error
@ -53,11 +56,18 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
return err
}
if keyBytes, ok := key.([]byte); ok {
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
}
case *rsa.PublicKey:
rsaKey = k
default:
return ErrInvalidKey
}
// Create hasher
hasher := m.Hash.New()
@ -65,9 +75,6 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
// Verify the signature
return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
} else {
return ErrInvalidKey
}
}
// 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) {
key, _ := ioutil.ReadFile("test/sample_key")
method := GetSigningMethod("RS256").(*SigningMethodRSA)