views:

3069

answers:

3

Ive looked everywhere on the internet and while some people claim to have found the solution, it either does not work or there is no Sample code to back it up. Does anyone know how to accept a self signed cert in java on the android? A code sample would be perfect.

Thanks, Faisal

+5  A: 

I have this functionality in exchangeIt, which connects to Microsoft exchange via WebDav. Here's some code to create an HttpClient which will connect to self signed cert's via SSL:

SchemeRegistry schemeRegistry = new SchemeRegistry();
// http scheme
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// https scheme
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

The EasySSLSocketFactory is here, and the EasyX509TrustManager is here.

The code for exchangeIt is open source, and hosted on googlecode here, if you have any issues. I'm not actively working on it anymore, but the code should work.

Brian Yarger
Your the best! Thanks, ill implement it really soon!
Faisal Abid
+4  A: 

Here's another way, without any extra classes:

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

private void trustEveryone() {
 try {
  HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
       public boolean verify(String hostname, SSLSession session) {
        return true;
       }});
  SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, new X509TrustManager[]{new X509TrustManager(){
   public void checkClientTrusted(X509Certificate[] chain,
     String authType) throws CertificateException {}
   public void checkServerTrusted(X509Certificate[] chain,
     String authType) throws CertificateException {}
   public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
   }}}, new SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(
    context.getSocketFactory());
 } catch (Exception e) { // should never happen
  e.printStackTrace();
 }
}
Chris Boyle
Where would you call this method?
Faisal Abid
You would call it anywhere before opening an https connection. Any connection using URL.openConnection / HttpsURLConnection should be affected.
Chris Boyle