Blog

Trust everyone

Added by Christoph Kappel about 1 month ago

Dealing with SSL is a pain, dealing with self-signed certificates is something perfectly suited for hell. One of the easiest way is to add your own custom CA certificate to the list of user-supplied CAs. Just copy the .crt file to your Android (>=4.x) device, double tap on it and install it the Certificate Installer.

That works properly for most of the apps with the funny side effect of a warning that informs you about being monitored by a third party.

..but sometimes this isn't enough and/or your own invocation of eg DefaultHttpClient won't work.

Just add this little method into your code, call it when you are sure you want to trust all certificates and never complain if that completely breaks your SSL chain of trust.

 1 private void
 2 trustEveryone()
 3 {
 4   try
 5     { 
 6       HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
 7         {
 8           public boolean
 9           verify(String hostname, SSLSession session)
10           {
11             return true;
12           }
13         }
14       );
15 
16       SSLContext context = SSLContext.getInstance("TLS");
17 
18       context.init(null, new X509TrustManager[]
19         {
20           new X509TrustManager()
21             {
22               public void checkClientTrusted(X509Certificate[] chain,
23                 String authType) throws CertificateException {}
24               public void checkServerTrusted(X509Certificate[] chain,
25                 String authType) throws CertificateException {}
26               public X509Certificate[] getAcceptedIssuers()
27               {
28                 return new X509Certificate[0];
29               }
30             }
31         }, new SecureRandom());
32 
33       HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
34     }
35   catch(Exception e)
36     {
37       e.printStackTrace();
38     }
39 }

Also available in: Atom RSS