title: Use PEM Encoded CA Cert on filesystem directly for HTTPS request?
body: <p>This is similar to <a href="https://stackoverflow.com/questions/2138940/import-pem-into-java-key-store">Import PEM into Java Key Store</a>. But the question's answers use OpenSSL for conversions and tools to import them into key stores on the file system.</p>
  
  <p>I'm trying to use a well formed X509 certificate as a trust anchor:</p>
  
  <pre><code>static String CA_FILE = "ca-rsa-cert.pem";
  
  public static void main(String[] args) throws Exception
  {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(CA_FILE), null);
  
      TrustManagerFactory tmf = TrustManagerFactory
                  .getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(ks);
  
      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);
  
      // Redirected through hosts file
      URL url = new URL("https://example.com:8443");
  
      HttpsURLConnection connection = (HttpsURLConnection) url
              .openConnection();
      connection.setSSLSocketFactory(context.getSocketFactory());
  
      ...
  }
  </code></pre>
  
  <p>When I attempt to run the program, I get an error:</p>
  
  <pre><code>$ java TestCert 
  Exception in thread "main" java.io.IOException: Invalid keystore format
      at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
      at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
      at java.security.KeyStore.load(KeyStore.java:1214)
      at TestCert.main(TestCert.java:30)
  </code></pre>
  
  <p>I also tried <code>KeyStore ks = KeyStore.getInstance("PEM");</code> and <code>getInstance("X509");</code>, but they did not work either.</p>
  
  <p>I know Java supports PEM and DER encoded certificates because that's what a web server sends to a client. But none of the <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#KeyStore" rel="nofollow noreferrer"><code>KeyStoreType</code></a>'s seem to match my needs, so I suspect I'm not using the right APIs for this.</p>
  
  <p>The reasons I want to use them directly and <em>not</em> import them into a long-lived <code>KeyStore</code> are:</p>
  
  <ol>
  <li>There are hundreds of PEM certs to test</li>
  <li>The certs are on my filesystem</li>
  <li>Using certs from the filesystem matches my workflow</li>
  <li>I don't want to to use <code>openssl</code> or <code>keytool</code></li>
  <li>I don't want to perform key store maintenance</li>
  </ol>
  
  <p>How does on take a well formed PEM encoded certificate on the filesystem and use it directly?</p>