title: How to generate RSA Private key from *pem string in Java
body: <p>I want to generate the private key from a string(a <code>.pem</code> file) in Java.</p>
  
  <pre><code>private static final String test = "-----BEGIN RSA PRIVATE KEY-----\n" +
           "MIIEpAIBAAKCAQEAvcCH8WsT1xyrZqq684VPJzOF3hN5DNbowZ96Ie//PN0BtRW2\n" +
  // and so on
           "-----END RSA PRIVATE KEY-----";
  
  try {
      String privKeyPEM = test.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
      privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
  
      byte [] encoded = Base64.decode(privKeyPEM);
  
      PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      PrivateKey privKey = kf.generatePrivate(keySpec);
  }
  catch (Exception e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p>The last line(generatePrivate function) is throwing this exception:</p>
  
  <pre><code>java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
      at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
      at java.security.KeyFactory.generatePrivate(Unknown Source)
      at Test.main(Test.java:52)
  Caused by: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
      at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
      at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
      at sun.security.rsa.RSAPrivateCrtKeyImpl.&lt;init&gt;(Unknown Source)
      at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(Unknown Source)
      at sun.security.rsa.RSAKeyFactory.generatePrivate(Unknown Source)
      ... 3 more
  </code></pre>
  
  <p>If I change the private key to the value from a <code>.der</code> file it works properly, but I need to generate the private key file from a <code>.pem</code> file.</p>
  
  <p>I attached a screenshot of the bytes printed as string(once hard-coded with \n and once hard-coded without \n) and once from the file.</p>
  
  <p><a href="https://i.stack.imgur.com/UxhMP.png" rel="nofollow noreferrer">Bigger Image</a></p>
  
  <p><img src="https://i.stack.imgur.com/UxhMP.png" alt="Output"></p>
  
  <p>The weird thing is that the output from the file is different to the output from the strings.</p>
  
  <p>If I try to encode a <code>.der</code> file with Base64, the result is different than the string in the <code>.pem</code> file. Why is that so?</p>