0

I have read a lot of bad examples on PEMParser:

int myFunc(String privateKeyFileName, char [] password) {
     File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
     PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
     Object object = pemParser.readObject();
     PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password);
     JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
     KeyPair kp;
     if (object instanceof PEMEncryptedKeyPair) {
        System.out.println("Encrypted key - we will use provided password");
        kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    } else {
        System.out.println("Unencrypted key - no password needed");
        kp = converter.getKeyPair((PEMKeyPair) object);
    }
}

Bouncy Castle : PEMReader => PEMParser

Also here: How to read .pem file to get private and public key https://www.codota.com/code/java/classes/org.bouncycastle.openssl.PEMParser https://www.programcreek.com/java-api-examples/?api=org.bouncycastle.openssl.PEMParser https://www.javatips.net/api/org.bouncycastle.util.io.pem.pemreader

Does BouncyCastle provide some factory method for this?

The only thing I found is: org.apache.sshd.common.keyprovider.FileKeyPairProvider (Apache Mina SSH Java client implementation). I think something like this could be a part of BouncyCastle itself or Apache Common libraries (fileutils / stringutils).

Is there any factory/builder method or some design pattern implementation or is everyone doing a production code like if (object instance of xxx) and solving the problems on the go?

  • 1
    I'm sorry but I do not understand your question. What kind of key(s) are you trying to read with Bouncy Castle's PEMParser (Private Key / Encrypted Private Key / RSA Private Key / Public Key / Certificate) ? BC's PEMParser is like a "Suice knife" that is been able to read a lot of formats... – Michael Fehr Aug 18 '20 at 18:08
  • All keys: Private Key / Encrypted Private Key / RSA Private Key / Public Key / Certificate – Lukáš Cyberluke Satin Aug 19 '20 at 08:27
  • So it is question about the library and more about architecture/design. I don't need help with the actual implementation how to read a key. The question is if there is some nicer code encapsulating this ugly piece of Java object with no interface and no design pattern. – Lukáš Cyberluke Satin Aug 21 '20 at 09:39
  • Can someone answer please? – Lukáš Cyberluke Satin Sep 08 '20 at 13:22

0 Answers0