From 5e00fbc8e7eb1af78d4a0ebce6ecf2394675bd99 Mon Sep 17 00:00:00 2001 From: Tom Anderson Date: Tue, 18 Apr 2023 02:29:03 +0930 Subject: [PATCH] enable jwt.ParsePublicKeyFromPEM to parse PKCS1 Public Key (#120) --- rsa_test.go | 19 +++++++++++++++++++ rsa_utils.go | 6 ++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/rsa_test.go b/rsa_test.go index cba4100..8773476 100644 --- a/rsa_test.go +++ b/rsa_test.go @@ -1,6 +1,11 @@ package jwt_test import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" "os" "reflect" "strings" @@ -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) @@ -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) { diff --git a/rsa_utils.go b/rsa_utils.go index 1966c45..b3aeebb 100644 --- a/rsa_utils.go +++ b/rsa_utils.go @@ -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 @@ -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 + } } }