title: HTTPS connection with client certificate in an android app
body: <p>I am trying to replace the currently working HTTP connection with a HTTPS connection in a Android app that I am writing. The additional security of a HTTPS connection is necessary and so I cannot ignore this step.</p>
  
  <p>I have the following:</p>
  
  <ol>
  <li>A server configured to establish a HTTPS connection, and require a client certificate
  
  <ul>
  <li>This server has a certificate that is issued by a standard large-scale CA. In short, if I access this connection via the browser in Android, it works fine because the devices truststore recognizes the CA. (So it's not self-signed)</li>
  </ul></li>
  <li>A client certificate that is essentially self-signed. (Issued by an internal CA)</li>
  <li>An Android app that loads this client certificate and attempts to connect to the aforementioned server, but has the following problems/properties:
  
  <ul>
  <li>The client can connect to the server when the server is configured to <strong>not</strong> require a client certificate. Basically, if I use <code>SSLSocketFactory.getSocketFactory()</code> the connection works fine, but the client certificate is a required part of this applications specifications, so:</li>
  <li>The client produces a <code>javax.net.ssl.SSLPeerUnverifiedException: No peer certificate</code> exception when I attempt to connect with my custom <code>SSLSocketFactory</code>, but I am not entirely certain why. This exception seems a little ambiguous after searching around the internet for various solutions to this.</li>
  </ul></li>
  </ol>
  
  <p>Here is the relavent code for the client:</p>
  
  <pre><code>SSLSocketFactory socketFactory = null;
  
  public void onCreate(Bundle savedInstanceState) {
      loadCertificateData();
  }
  
  private void loadCertificateData() {
      try {
          File[] pfxFiles = Environment.getExternalStorageDirectory().listFiles(new FileFilter() {
              public boolean accept(File file) {
                  if (file.getName().toLowerCase().endsWith("pfx")) {
                      return true;
                  }
                  return false;
              }
          });
  
          InputStream certificateStream = null;
          if (pfxFiles.length==1) {
              certificateStream = new FileInputStream(pfxFiles[0]);
          }
  
          KeyStore keyStore = KeyStore.getInstance("PKCS12");
          char[] password = "somePassword".toCharArray();
          keyStore.load(certificateStream, password);
  
          System.out.println("I have loaded [" + keyStore.size() + "] certificates");
  
          KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
          keyManagerFactory.init(keyStore, password);
  
          socketFactory = new SSLSocketFactory(keyStore);
      } catch (Exceptions e) {
          // Actually a bunch of catch blocks here, but shortened!
      }
  }
  
  private void someMethodInvokedToEstablishAHttpsConnection() {
      try {
          HttpParams standardParams = new BasicHttpParams();
          HttpConnectionParams.setConnectionTimeout(standardParams, 5000);
          HttpConnectionParams.setSoTimeout(standardParams, 30000);
  
          SchemeRegistry schRegistry = new SchemeRegistry();
          schRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
          schRegistry.register(new Scheme("https", socketFactory, 443));
          ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(standardParams, schRegistry);
  
          HttpClient client = new DefaultHttpClient(connectionManager, standardParams);
          HttpPost request = new HttpPost();
          request.setURI(new URI("https://TheUrlOfTheServerIWantToConnectTo));
          request.setEntity("Some set of data used by the server serialized into string format");
          HttpResponse response = client.execute(request);
          resultData = EntityUtils.toString(response.getEntity());
      } catch (Exception e) {
          // Catch some exceptions (Actually multiple catch blocks, shortened)
      }
  }
  </code></pre>
  
  <p>I have verified that, yes indeed the keyStore loads a certificate and is all happy with that.</p>
  
  <p>I have two theories as to what I'm missing from reading about HTTPS/SSL connections, but as this is really my first foray, I am a little puzzled as to what I actually need to resolve this issue.</p>
  
  <p>The first possibility, as far as I can tell, is that I need to configure this SSLSocketFactory with the devices' truststore that includes all of the standard Intermediate and endpoint Certificate Authorities. That is, the device's default of <code>SSLSocketFactory.getSocketFactory()</code> loads some set of CAs into the factory's truststore that is used to trust the server when it sends its certificate, and that is what is failing in my code, because I do not properly have the trust store loaded. If this is true, how would I best go about loading this data?</p>
  
  <p>The second possibility is due to the fact that the client certificate is self-signed (or issued by an internal certificate authority -- correct me if I'm wrong, but these really amount to the same thing, for all intents and purposes here). It is in fact <em>this</em> truststore that I am missing, and basically I need to provide a way for the server to validate the certificate with the internal CA, and also validate that this internal CA is in fact <em>"trustable"</em>. If this is true, exactly what sort of thing am I looking for? I have seen some reference to this that makes me believe this may be my problem, as in <a href="https://stackoverflow.com/questions/1666052/java-https-client-certificate-authentication">here</a>, but I am truly not certain. If this is indeed my problem, what would I ask for from the person who maintains the internal CA, and then how would I add this to my code so that my HTTPS connection would work?</p>
  
  <p>The third, and hopefully less possible solution, is that I'm entirely wrong about some point here and have missed a crucial step or am completely neglecting a portion of HTTPS/SSL that I just don't currently have any knowledge of. If this is the case, could you please provide me with a bit of a direction so that I can go and learn what it is I need to learn?</p>
  
  <p>Thanks for reading!</p>