Skip to content

Commit 5e00fbc

Browse files
authored
enable jwt.ParsePublicKeyFromPEM to parse PKCS1 Public Key (#120)
1 parent 6c9126f commit 5e00fbc

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

rsa_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
package jwt_test
22

33
import (
4+
"bytes"
5+
"crypto/rand"
6+
"crypto/rsa"
7+
"crypto/x509"
8+
"encoding/pem"
49
"os"
510
"reflect"
611
"strings"
@@ -115,6 +120,17 @@ func TestRSAKeyParsing(t *testing.T) {
115120
pubKey, _ := os.ReadFile("test/sample_key.pub")
116121
badKey := []byte("All your base are belong to key")
117122

123+
randomKey, err := rsa.GenerateKey(rand.Reader, 2048)
124+
if err != nil {
125+
t.Errorf("Failed to generate RSA private key: %v", err)
126+
}
127+
128+
publicKeyBytes := x509.MarshalPKCS1PublicKey(&randomKey.PublicKey)
129+
pkcs1Buffer := new(bytes.Buffer)
130+
if err = pem.Encode(pkcs1Buffer, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}); err != nil {
131+
t.Errorf("Failed to encode public pem: %v", err)
132+
}
133+
118134
// Test parsePrivateKey
119135
if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil {
120136
t.Errorf("Failed to parse valid private key: %v", e)
@@ -149,6 +165,9 @@ func TestRSAKeyParsing(t *testing.T) {
149165
t.Errorf("Parsed invalid key as valid private key: %v", k)
150166
}
151167

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

154173
func BenchmarkRSAParsing(b *testing.B) {

rsa_utils.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr
7575
return pkey, nil
7676
}
7777

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

@@ -91,7 +91,9 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
9191
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
9292
parsedKey = cert.PublicKey
9393
} else {
94-
return nil, err
94+
if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil {
95+
return nil, err
96+
}
9597
}
9698
}
9799

0 commit comments

Comments
 (0)