Skip to content

Commit

Permalink
enable jwt.ParsePublicKeyFromPEM to parse PKCS1 Public Key (#120)
Browse files Browse the repository at this point in the history
  • Loading branch information
twocs authored Apr 17, 2023
1 parent 6c9126f commit 5e00fbc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
19 changes: 19 additions & 0 deletions rsa_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package jwt_test

import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
"reflect"
"strings"
Expand Down Expand Up @@ -115,6 +120,17 @@ func TestRSAKeyParsing(t *testing.T) {
pubKey, _ := os.ReadFile("test/sample_key.pub")
badKey := []byte("All your base are belong to key")

randomKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Errorf("Failed to generate RSA private key: %v", err)
}

publicKeyBytes := x509.MarshalPKCS1PublicKey(&randomKey.PublicKey)
pkcs1Buffer := new(bytes.Buffer)
if err = pem.Encode(pkcs1Buffer, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}); err != nil {
t.Errorf("Failed to encode public pem: %v", err)
}

// Test parsePrivateKey
if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil {
t.Errorf("Failed to parse valid private key: %v", e)
Expand Down Expand Up @@ -149,6 +165,9 @@ func TestRSAKeyParsing(t *testing.T) {
t.Errorf("Parsed invalid key as valid private key: %v", k)
}

if _, err := jwt.ParseRSAPublicKeyFromPEM(pkcs1Buffer.Bytes()); err != nil {
t.Errorf("failed to parse RSA public key: %v", err)
}
}

func BenchmarkRSAParsing(b *testing.B) {
Expand Down
6 changes: 4 additions & 2 deletions rsa_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr
return pkey, nil
}

// ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key
// ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var err error

Expand All @@ -91,7 +91,9 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey
} else {
return nil, err
if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil {
return nil, err
}
}
}

Expand Down

0 comments on commit 5e00fbc

Please sign in to comment.