Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PEM.java fails with NPE if certificate file is of type BEGIN ENCRYPTED PRIVATE KEY #44

Open
kingsfleet opened this issue Jul 24, 2020 · 1 comment

Comments

@kingsfleet
Copy link

kingsfleet commented Jul 24, 2020

In this case object.getPEMObjectType will return null, causing a NPE in the case statement.

public static PrivateKey readPrivateKey(final InputStream is) throws InvalidKeySpecException, IOException {

      final List<PEMObject> objects = readPEMObjects(is);
       for (final PEMObject object : objects) {
           switch (object.getPEMObjectType()) {
               case PRIVATE_KEY_PKCS1:
                   return RSA.privateKeyFromPKCS1(object.getDerBytes());
               case PRIVATE_EC_KEY_PKCS8:
                   return EC.privateKeyFromPKCS8(object.getDerBytes());
               case PRIVATE_KEY_PKCS8:
                   try {
                       return RSA.privateKeyFromPKCS8(object.getDerBytes());
                   } catch (InvalidKeySpecException e) {
                       return EC.privateKeyFromPKCS8(object.getDerBytes());
                   }
               default:
                   break;
           }
       }
       throw new IllegalArgumentException("Found no private key");
   }

perhaps:

Stream.of(readPEMObjects(is))
   .map(PEMObject:getPEMObjectType)
   .filter(Objects::nonNull)
   .flatMap(PEM:parsePemObject)
   .findFirst().orElseThrow(() -> throw new IllegalArgumentException("Found no private key"));

private static Stream<PrivateKey> parsePemObject(PEMObject object) {
   PrivateKey found;
    switch (object.getPEMObjectType()) {
                case PRIVATE_KEY_PKCS1:
                    found = RSA.privateKeyFromPKCS1(object.getDerBytes());
                case PRIVATE_EC_KEY_PKCS8:
                    found = EC.privateKeyFromPKCS8(object.getDerBytes());
                case PRIVATE_KEY_PKCS8:
                    try {
                        found = RSA.privateKeyFromPKCS8(object.getDerBytes());
                    } catch (InvalidKeySpecException e) {
                        found = EC.privateKeyFromPKCS8(object.getDerBytes());
                    }
                default:
                    break;
            }
   return Optional.ofNullable(found).map(Stream::of).orElseGet(Stream::empty);
}
@jeanouii
Copy link
Member

Looks like a good improvement.
Would you like to create a PR for it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants