title: How to get the java.security.PrivateKey object from RSA Privatekey.pem file?
body: <p>I have a RSA private key file (OCkey.pem). Using java i have to get the private key from this file. this key is generated using the below openssl command. 
  Note : I can't change anything on this openssl command below.</p>
  
  <pre><code>openssl&gt; req -newkey rsa:1024 -sha1 -keyout OCkey.pem -out OCreq.pem -subj "/C=country/L=city/O=OC/OU=myLab/CN=OCserverName/" -config req.conf
  </code></pre>
  
  <p>The certificate looks like below.<BR></p>
  
  <blockquote>
    <p>/////////////////////////////////////////////////////////// <BR>
    bash-3.00$ less OCkey.pem <BR>
    -----BEGIN RSA PRIVATE KEY----- <BR> Proc-Type: 4,ENCRYPTED<BR> DEK-Info: DES-EDE3-CBC,EA1DBF8D142621BF<BR></p>
    
    <p>BYyZuqyqq9+L0UT8UxwkDHX7P7YxpKugTXE8NCLQWhdS3EksMsv4xNQsZSVrJxE3<BR>
    Ft9veWuk+PlFVQG2utZlWxTYsUVIJg4KF7EgCbyPbN1cyjsi9FMfmlPXQyCJ72rd<BR>
    ...<BR> ...<BR>
    cBlG80PT4t27h01gcCFRCBGHxiidh5LAATkApZMSfe6BBv4hYjkCmg== <BR>
    -----END RSA PRIVATE KEY-----<BR> //////////////////////////////////////////////////////////////</p>
  </blockquote>
  
  <p>Following is what I tried </p>
  
  <pre><code>byte[] privKeyBytes = new byte[(int)new File("C:/OCkey.pem").length()]; 
  PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(privKeyBytes));
  </code></pre>
  
  <p>but getting </p>
  
  <blockquote>
    <p>"java.security.spec.InvalidKeySpecException:
    java.security.InvalidKeyException: invalid key format"</p>
  </blockquote>
  
  <p>Please help.</p>