title: How can I read RSA keys in Java?
body: <p>I am trying to read the RSA public and private keys files in Java.</p>
  
  <p>My RSA public and private key is generated using PuttyGen. (SSH-2 RSA, 1024 bits)</p>
  
  <p>The code I am using for reading file is:</p>
  
  <pre><code>//public key
  pubkeyBytes = getBytesFromFile(new File(pubKeyfileName));
  KeySpec pubSpec = new X509EncodedKeySpec(pubkeyBytes);
  RSAPublicKey pubKey =(RSAPublicKey) rsakeyFactory.generatePublic(pubSpec);
  
  //private key
  privkeyBytes = getBytesFromFile(new File(privKeyfileName));
  PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privkeyBytes);
  PrivateKey privKey = rsakeyFactory.generatePrivate(privSpec);
  </code></pre>
  
  <p>It throws: </p>
  
  <pre><code>java.security.InvalidKeyException: invalid key format
      at sun.security.x509.X509Key.decode(Unknown Source)
  </code></pre>