title: RSA encryption :InvalidKeyException: invalid key format
body: <p>I have to read pem key files to get RSA Public key,and then use them to encrypt.
  I can do this using openssl and convert pem file to der file.
  and then load my key using X509EncodedKeySpec and PKCS8EncodedKeySpec.
  But I don't want to do this because pem is the user key exchange format.
  user can register it's own key can like this :</p>
  
  <pre><code>--BEGIN PUBLIC KEY-- MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGi0/vKrSIIQMOm4atiw+2s8tSojOKHsWJU3oPTm
  
  b1a5UQIH7CM3NgtLvUF5DqhsP2jTqgYSsZSl+W2RtqCFTavZTWvmc0UsuK8tTzvnCXETsnpjeL13
  
  Hul9JIpxZVej7b6KxgyxFAhuz2AGscvCXnepElkVh7oGOqkUKL7gZSD7AgMBAAE=
  
  --END PUBLIC KEY--
  </code></pre>
  
  <p>and this key is store in a database in this format...</p>
  
  <p>Here is the code I have tried..</p>
  
  <pre><code>File pubKeyFile=new File("D:/public_key.pem");
  DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
  byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
  dis.readFully(pubKeyBytes);
  dis.close();
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
  RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
  </code></pre>
  
  <p>I am getting exception as</p>
  
  <pre><code>java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
  </code></pre>
  
  <p>As I am completely new to encryption concepts can anyone please help me to solve this exception?</p>
  
  <p>Many thanks.</p>