title: InvalidKeySpecException: How do I extract a private key from a .der file?
body: <p>I have a private key file in the .der format. I'm trying to save this private key as a PrivateKey object (with Java) like this:</p>
  
  <pre><code>PrivateKey clientPrivKey = getPrivateKeyFromKeyFile("C:\\Users\\Bob\\Desktop\\Assignments\\Project\\VPN Project\\src\\client-private.der");
  </code></pre>
  
  <p>This is what the getPrivateKeyFromKeyFile method looks like:</p>
  
  <pre><code>private static PrivateKey getPrivateKeyFromKeyFile(String keyfile) throws Exception
      {
          Path path = Paths.get(keyfile);
          byte[] privKeyByteArray = Files.readAllBytes(path);
          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
          KeyFactory keyFactory = KeyFactory.getInstance("RSA");
          PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec); 
          return myPrivKey;
      }
  </code></pre>
  
  <p>But when I try this, I keep getting InvalidKeySpecException because of this line of code:</p>
  
  <pre><code>PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);
  </code></pre>
  
  <p>I'm not sure what's the issue here. I opened up the private key file and everything looks fine. It starts with <code>-----BEGIN RSA PRIVATE KEY-----</code> and ends with <code>-----END RSA PRIVATE KEY-----</code>.</p>
  
  <p>And in case it's relevant, I created this private key using this OpenSSL command:</p>
  
  <pre><code>genrsa -out client-private.der 2048
  </code></pre>