4

I have a PEM Key and I want to get a KeyPair with it and bouncycastle. I found this code which seems good but I have a cast exception.

function loadKey() {
    File privateKeyFile = new File(keyPath);
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    PEMDecryptorProvider decProv = new     JcePEMDecryptorProviderBuilder().build(password.toCharArray());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    Object object = pemParser.readObject();
    KeyPair kp;

    if (object instanceof PEMEncryptedKeyPair) {
        Logger.info("Encrypted key - we will use provided password");
        kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    }
    else {
        Logger.info("Unencrypted key - no password needed");    
        kp = converter.getKeyPair((PEMKeyPair) object);
    }

    return kp;
}

And it returns me : Unencrypted key - no password needed org.bouncycastle.asn1.x509.SubjectPublicKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair

I tried several methods but i didn't succeed.

Thanks to help me :)

3
  • Are you sure the PEM you're referencing is a private key? I'm using the same method with no difficulty.
    – Dave G
    Commented Mar 27, 2013 at 12:24
  • I'm not sure, I'm a total newbie with keys. How could I know it ? Commented Mar 27, 2013 at 12:41
  • 1
    Well based on the error you're getting - it sounds like you're decoding a certificate not a private key.
    – Dave G
    Commented Mar 27, 2013 at 13:41

2 Answers 2

6

If you have a private key that has passphrase you might get this exception. Try removing the passphrase:

openssl rsa -in /path/to/originalkeywithpass.key -out /path/to/newkeywithnopass.key
0

You can use below code

PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();

For example:

public PrivateKey getKeyFromClassPath(String filename) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream stream = loader.getResourceAsStream("certificates/" + filename);
    if (stream == null) {
        throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    try {
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pp = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        pp.close();
        return kp.getPrivate();
    } catch (IOException ex) {
        throw new CertificateException("Could not read private key from classpath", ex);
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.