title: Extracting Private key from pkcs12 and text encryption
body: <p>I have .p12 file, I am extracting the private key using openssl, I have a password for extracting it. </p>
  
  <pre><code>openssl pkcs12 -in my.p12 -nocerts -out privateKey.pem
  </code></pre>
  
  <p>And after I get my private key, I'm trying to use that key for encryption:</p>
  
  <pre><code> public static void main(String[] args) throws Exception {
          Security.addProvider(new BouncyCastleProvider());
          KeyPair keyPair = readKeyPair(privateKey, "testpassword".toCharArray());
          Cipher cipher = Cipher.getInstance("RSA");
          cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
          byte[] textEncrypted = cipher.doFinal("hello world".getBytes());
          System.out.println("encrypted: "+new String(textEncrypted));
          cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
          byte[] textDecrypted = cipher.doFinal(textEncrypted);
          System.out.println("decrypted: "+new String(textDecrypted));
      }
  
      private static KeyPair readKeyPair(File privateKey, char[] keyPassword) throws IOException {
          FileReader fileReader = new FileReader(privateKey);
          PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword));
          try {
              return (KeyPair) r.readObject(); // this returns null
          } catch (IOException ex) {
              throw new IOException("The private key could not be decrypted", ex);
          } finally {
              r.close();
              fileReader.close();
          }
      }
  </code></pre>
  
  <p><strong>r.readObject();</strong> returns null. But when I create a private key by myself by this command:</p>
  
  <pre><code>openssl genrsa -out privkey.pem 2048
  </code></pre>
  
  <p>The above code works fine. </p>
  
  <ul>
  <li>How can I extract private key from p12 file properly?</li>
  <li>Or is there any way to use p12 file for encrypt/decrypt the text
  without extracting through command line?</li>
  </ul>
  
  <p><em>I know it is just <a href="http://en.wikipedia.org/wiki/PKCS_%E2%99%AF12" rel="nofollow">PKCS#12</a> is just archaive file which stores keys.</em></p>