title: How do i read the private key in java from a pfx certificate
body: <p>I am trying to read a private key  i java .I learned inorder to do that i have to extract  private key from my full certificate in pfx format.
  I have tried  the below open ssl command to convert pfx to pem and then to pk8 , but when i tried to read the key in java , it says invalid key format </p>
  
  <p>convert pfx to pem</p>
  
  <pre><code>      openssl pkcs12 -in C:\Documents\xbox-token\conversion\xbox
    token-FullCert.pfx -nocerts -out C:\Documents\xbox-token\conversion\xboxkey.pem
  </code></pre>
  
  <p>Removing password protection</p>
  
  <pre><code>openssl rsa -in C:\Documents\xbox-token\conversion\xboxkey.pem  -out C:\Documents\xbox-token\conversion\xboxkey.pem
  </code></pre>
  
  <p>Convert pem to pk8 </p>
  
  <pre><code>openssl pkcs8 -topk8 -in C:\Documents\xbox-token\conversion\xboxkey.pem -out C:\Documents\xbox-token\conversion\xboxprv.pk8
  </code></pre>
  
  <p>In the java code </p>
  
  <pre><code>  byte[] encodedPrivateKey=null;
      File privateKeyFile = new File("C:/Documents/xbox-token/conversion/xboxprv.pk8");
      FileInputStream inputStreamPrivateKey = null;
      try {
          inputStreamPrivateKey = new FileInputStream(privateKeyFile);
            encodedPrivateKey = new byte[(int)privateKeyFile.length()];
              inputStreamPrivateKey.read(encodedPrivateKey);
              inputStreamPrivateKey.close();
      } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  
  
      // Create the private key.
      PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
      System.out.println(encodedPrivateKey);
      System.out.println(privateKeySpec);
      RSAPrivateKey privateKey = null;
      try {
          privateKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec);
      } catch (InvalidKeySpecException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  </code></pre>
  
  <p>I am getting an java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format</p>
  
  <p>Can any one help </p>