title: When to use X509EncodedKeySpec vs RSAPublicKeySpec?
body: <p>I have a certificate in a text file, its contents look like:</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  xxxx
  xxxx
  xxxx
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>I believe this is a pem encoded certificate? So I want to load it now, I'm trying the following:</p>
  
  <pre><code>X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
      readFileToByteArray("keyfile"));
  </code></pre>
  
  <p>but I get an InvalidKeySpecException. </p>
  
  <p>If I load the file, cut off the begin/end header/footer, then base64 decode the 'xxxx' contents, I don't get any complaints:</p>
  
  <pre><code>String contents = readFileToString("keyfile");
  contents = contents.replace("-----BEGIN PUBLIC KEY-----", "");
  contents = contents.replace("-----END PUBLIC KEY-----", "");
  byte[] prepared = Base64.decode(contents);
  
  // ok.
  X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(prepared);
  </code></pre>
  
  <p>is this the right way to load the key file? I see there's also a <a href="http://docs.oracle.com/javase/7/docs/api/java/security/spec/RSAPublicKeySpec.html" rel="noreferrer">RSAPublicKeySpec</a> class, which, based on the name, seems like something I'd be interested in here. But I believe it is only for generating certificates, not reading existing ones?</p>
  
  <p>Thanks</p>