title: Connect to a https site with a given p12 certificate
body: <p>The server side gave me a <code>.p12</code> certificate file which I've clicked and installed on my machine and then I can access the <code>HTTPS</code> site through browser. Now they want me to crawl their site with the certificate given. I'm stuck at the very first stage of it, trying to get the <code>inputStream</code> from the <code>httpsURLConnection</code>. The site has no login. It only checks if you have the certificate or not.</p>
  
  <p>What I've done so far was to use Firefox to export out the certificate in a <code>.crt</code> file format. Then I used the keytool command to import it (the <code>.crt</code> file, not the <code>.p12</code>) into java keystore. Then in the code:</p>
  
  <pre><code>KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  File ksFile = new File(keystorePath);
  in = new FileInputStream(ksFile);
  ks.load(in, "changeit".toCharArray());
  X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
  
  SSLContext sc = SSLContext.getInstance("TLS");
  sc.init(null, trustAllCerts, new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  
  HttpsURLConnection con = (HttpsURLConnection) (new URL(urlString)).openConnection();
  con.connect();
  con.getInputStream();
  con.disconnect();
  </code></pre>
  
  <p>The <code>getInputStream()</code> will give me 403 error forbidden access. I've searched through other related topics and are actually deeply more confused than before reading them. Would greatly appreciate answers.</p>
  
  <p>Additional Details:</p>
  
  <ul>
  <li>I've only just instantiated the certificate, and have not let the program knows any sort of keys (private, public, etc.). So what I believe I must present these keys to the server, letting it know I'm actually holding the certificate. I have absolutely no idea how to do this, both logic and syntax wise.</li>
  <li>I've tried keytool command to import the .p12 cert file into the keystore but somehow, the -pkcs12 option is not recognized by the keytool. Any idea on how to directly use this .p12 cert would be great as well.</li>
  <li>trustAllCert is a one element array of TrustMangers which does not validate anything (trust all). I don't know if I should continue to use this. In fact, now I actually have a single cert to trust. What is the proper way to write a trustManger in this case?</li>
  <li>I have no control over the server side. All I was given are the URL to access their site, which is under HTTPS protocol, and a .p12 certificate. The site has no login. If the certificate is installed, I can go in.</li>
  </ul>