title: How to read a password encrypted key with java?
body: <p>I have private key stored in file in PKCS8 DER format and protected by password. What is the easiest way to read it? </p>
  
  <p>Here is the code I use to load unencrypted one:</p>
  
  <pre><code>InputStream in = new FileInputStream(privateKeyFilename);
  byte[] privateKeydata = new byte[in.available()];
  in.read(privateKeydata);
  in.close();
  KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(privateKeydata);
  PrivateKey privateKey = privateKeyFactory.generatePrivate(encodedKeySpec);
  </code></pre>
  
  <p>It works fine for unencrypted keys with the same specification. By the way, I am using BouncyCastle.</p>
  
  <p>I can view this private key using following openssl command</p>
  
  <pre><code>openssl pkcs8 -in ./privatekey.key -inform DER -passin pass:thisismypass
  </code></pre>
  
  <p>Please, Help!!!</p>
  
  <p><strong>I,ve posted some solutions in my own answer to this topic. But I keep question unanswered in case anybody can help with making it work without extra library, just BouncyCastle.</strong> </p>