forked from mirror/jwt
can now pass a PrivateKey to SigningMethodRSA.Sign
Conflicts: rsa.go
This commit is contained in:
parent
c9b532b51b
commit
dc2f34cdb1
20
rsa.go
20
rsa.go
|
@ -71,17 +71,22 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
|
|||
}
|
||||
|
||||
// Implements the Sign method from SigningMethod
|
||||
// For this signing method, must be PEM encoded PKCS1 or PKCS8 RSA private key
|
||||
// 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) Sign(signingString string, key interface{}) (string, error) {
|
||||
var err error
|
||||
|
||||
if keyBytes, ok := key.([]byte); ok {
|
||||
// Key
|
||||
var rsaKey *rsa.PrivateKey
|
||||
if rsaKey, err = m.parsePrivateKey(keyBytes); err != nil {
|
||||
|
||||
switch k := key.(type) {
|
||||
case []byte:
|
||||
if rsaKey, err = m.parsePrivateKey(k); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
case *rsa.PrivateKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
// Create the hasher
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
@ -94,9 +99,6 @@ func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string,
|
|||
}
|
||||
}
|
||||
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
|
||||
// Parse PEM encoded PKCS1 or PKCS8 public key
|
||||
func (m *SigningMethodRSA) parsePublicKey(key []byte) (*rsa.PublicKey, error) {
|
||||
var err error
|
||||
|
|
18
rsa_test.go
18
rsa_test.go
|
@ -78,6 +78,24 @@ func TestRSASign(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRSAWithPreParsedPrivateKey(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
method := GetSigningMethod("RS256").(*SigningMethodRSA)
|
||||
parsedKey, err := method.parsePrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testData := rsaTestData[0]
|
||||
parts := strings.Split(testData.tokenString, ".")
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), parsedKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", testData.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAKeyParsing(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
|
|
Loading…
Reference in New Issue