PEMParser update

In my last post I talked about using PEMParser to load private keys from OpenSSL PEM files. After further testing I discovered I needed to refine the code a little.

There appears to be a couple of different ways the private key can be encoded in the file. I discovered this after generating some new test keys only to find they didn’t work with my existing code.

Object privatekey = parser.readObject();

if (privatekey instanceof PEMEncryptedKeyPair) {
     try {
	privatekey = ((PEMEncryptedKeyPair)privatekey).decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(passphrase));
     } catch (Exception e) {
	throw new InvalidPassphraseException(e);
     }
} else if(privatekey instanceof PKCS8EncryptedPrivateKeyInfo) {
     try {
	privatekey = converter.getPrivateKey(((PKCS8EncryptedPrivateKeyInfo)privatekey).decryptPrivateKeyInfo(new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase)));
     } catch (Exception e) {
	throw new InvalidPassphraseException(e);
     }
}

if (privatekey instanceof PEMKeyPair) {
	return loadKeyPair((PEMKeyPair)privatekey);
} else if(privatekey instanceof RSAPrivateCrtKey){
	return loadKeyPair((RSAPrivateCrtKey)privatekey);
} else {
	throw new FileFormatException("The file doesn't seem to have any supported key types obj=" + privatekey);
}