title: Encrypting with RSA private key in Java
body: <p>I'm trying to encrypt some content with an RSA private key.  </p>
  
  <p>I'm following this example:
  <a href="http://www.junkheap.net/content/public_key_encryption_java" rel="nofollow noreferrer">http://www.junkheap.net/content/public_key_encryption_java</a><br>
  <br>
  but converting it to use private keys rather than public.  Following that example, I think what I need to do is:</p>
  
  <ul><li>Read in a DER-format private key</li>
  <li>Generate a PCKS8EncodedKeySpec</li>
  <li>call generatePrivate() from KeyFactory to get a private key object</li>
  <li>Use that private key object with the Cipher object to do the encryption</li>
  </ul>
  
  <p>So, the steps:</p>
  
  <p>The key was generated from openssl with:</p>
  
  <p><code>openssl genrsa -aes256 -out private.pem 2048</code></p>
  
  <p>and then was converted to DER format with:</p>
  
  <p><code>openssl rsa -in private.pem -outform DER -out private.der</code></p>
  
  <p>I generate the PKCS8EncodedKeySpec with:</p>
  
  <pre><code>byte[] encodedKey = new byte[(int)inputKeyFile.length()];
  
  try {
      new FileInputStream(inputKeyFile).read(encodedKey);
  } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
  
  PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
  return privateKeySpec;
  </code></pre>
  
  <p>And then generate the private key object with:</p>
  
  <pre><code>PrivateKey pk = null;
  
  try {
      KeyFactory kf = KeyFactory.getInstance(RSA_METHOD);
      pk = kf.generatePrivate(privateKeySpec);
  } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  } catch (InvalidKeySpecException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
  return pk;
  </code></pre>
  
  <p>However, on the call to:</p>
  
  <pre><code>pk = kf.generatePrivate(privateKeySpec);
  </code></pre>
  
  <p>I get:</p>
  
  <pre><code>java.security.spec.InvalidKeySpecException: Unknown key spec.
  at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePrivate(DashoA12275)
  at com.sun.net.ssl.internal.ssl.JSA_RSAKeyFactory.engineGeneratePrivate(DashoA12275)
  at java.security.KeyFactory.generatePrivate(KeyFactory.java:237)
  </code></pre>
  
  <p>Questions:</p>
  
  <ul>
  <li>Is the general approach right?</li>
  <li>Is the PCKS8EncodedKeySpec the right keyspec to use?</li>
  <li>Any thoughts on the invalid key spec error?</li>
  </ul>