From 33523225e13f038716f49a9dfa7b4da0aa442daa Mon Sep 17 00:00:00 2001 From: Simon Jefford Date: Thu, 7 Aug 2014 08:45:21 +0100 Subject: [PATCH] can now pass a PublicKey to SigningMethodRSA.Verify --- rsa.go | 29 ++++++++++++++++++----------- rsa_test.go | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/rsa.go b/rsa.go index 0bfdda5..bb71685 100644 --- a/rsa.go +++ b/rsa.go @@ -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,21 +56,25 @@ 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 { + var rsaKey *rsa.PublicKey + + switch k := key.(type) { + case []byte: + if rsaKey, err = m.parsePublicKey(k); err != nil { return err } - - // Create hasher - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) - } else { + case *rsa.PublicKey: + rsaKey = k + default: 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 diff --git a/rsa_test.go b/rsa_test.go index b2f2653..7bbacf3 100644 --- a/rsa_test.go +++ b/rsa_test.go @@ -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)