title: Get KeyPair from PEM Key with BouncyCastle
body: <p>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.</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>And it returns me :
  Unencrypted key - no password needed
  org.bouncycastle.asn1.x509.SubjectPublicKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair</p>
  
  <p>I tried several methods but i didn't succeed.</p>
  
  <p>Thanks to help me :)</p>