Skip to content

Code comment for jwt.ParseRSAPublicKeyFromPEM incorrect #119

@twocs

Description

@twocs

The code comment for rsa_utils.go says it's for a PKCS1 or PKCS8 public key (ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key), but the function uses x509.ParsePKIXPublicKey instead. I was unable to get a PKCS1 public key despite the code comment, and basically just copied the entire function and swapped it from x509.ParsePKIXPublicKey to x509.ParsePKCS1PublicKey, which works. I am not clear but it seems that it's not matching the code comment and it took me quite some time to figure out why I couldn't parse my RSA Public Key (it wasn't accepted on jwt.io).

I suspect that the problem is not with the code comment, but with the implementation. Or am I doing something wrong that the parsing of a pem with PKCS1 encoding doesn't work using x509.ParsePKIXPublicKey but does work with x509.ParsePKCS1PublicKey?

func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {

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

	// Parse PEM block
	var block *pem.Block
	if block, _ = pem.Decode(key); block == nil {
		return nil, ErrKeyMustBePEMEncoded
	}

	// Parse the key
	var parsedKey interface{}
	if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
		if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
			parsedKey = cert.PublicKey
		} else {
			return nil, err
		}
	}

If we compare to

func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {

private key explicitly tries both functions.

	if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
		if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
			return nil, err
		}
	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions