title: JAVA: How to save a private key in a pem file with password protection
body: <p>I am trying to save a private key in a <code>pem</code> file, protected with a password. The problem is, the <code>pem</code> file is created and I
  can even open it with openssl but, no password is asked!</p>
  
  <p>Here is the code:</p>
  
  <pre><code>KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
  keygen.initialize(2048);
  KeyPair keypair = keygen.generateKeyPair();
  
  PrivateKey privKey = keypair.getPrivate();
  
  PKCS8Generator encryptorBuilder = new PKCS8Generator(privKey);
  encryptorBuilder.setPassword("testing".toCharArray());
  PEMWriter writer = new PEMWriter(new FileWriter(new File("pk.pem")));
  PemObject obj = encryptorBuilder.generate();
  
  writer.writeObject(obj);
  writer.flush();
  writer.close();
  </code></pre>
  
  <p>After it executes, I try to open the <code>pk.pem</code> file </p>
  
  <pre><code>openssl rsa -in pk.pem -check
  </code></pre>
  
  <p>and it gives:</p>
  
  <pre><code>RSA key ok
  writing RSA key
  -----BEGIN RSA PRIVATE KEY-----
  (... some key appears here ...)
  -----END RSA PRIVATE KEY-----
  </code></pre>
  
  <p>It was suppose to ask for the password before giving access to the private key! 
  Can some one please help me?</p>