0

I hope guys you can help me with this problem, I do all the research and tried anything I saw but it just cannot resolve my problem. What I want to do is that to trust all the SSL certicates in my app. All the solutions I saw was using URLHttpConnection but I need a working solution for AndroidHttpClient. See my code below:

AndroidHttpClient httpClient = null;
HttpResponse httpResponse;
Bundle responseBundle;
try{
        httpClient = AndroidHttpClient.newInstance("android");
        httpClient = addCustomCertificate(httpClient);
        httpResponse = httpClient.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            String response = convertStreamToString(instream);
            responseBundle = new Bundle();
            responseBundle.putString("result", response);
            responseBundle.putInt("responseCode", responseCode);
            receiver.send(method, responseBundle);

            instream.close(); 
            httpClient.close();
        }
}

//====

private AndroidHttpClient addCustomCertificate(AndroidHttpClient client)
    {
        SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();

        try
        {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            sf = new SSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        }
        catch (Exception t)
        {
            t.printStackTrace();
        }

        client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443));

        return client;
    }

But I'm always getting the error show in the image I captured in my logs. I cannot figure out what other solution can I do.enter image description here

lolliloop
  • 389
  • 8
  • 23
  • Have you tried http://stackoverflow.com/questions/18126372/safely-fixing-javax-net-ssl-sslpeerunverifiedexception-no-peer-certificate and http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https – Remees M Syde Jul 09 '15 at 05:36
  • @RemeesMSyde yes, actually the code I created came from those. – lolliloop Jul 09 '15 at 05:44
  • http://janis.peisenieks.lv/en/76/english-making-an-ssl-connection-via-android/ – Ankitkumar Makwana Jul 09 '15 at 06:29

2 Answers2

1

Please check below 1,2,3 Method i m using it for get SSSl Certificate getNewHttpClient and working fine for me.hope will help you.

1.Api calling Function, its need to call with Asynck Task doInBackground()

public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair ) {
        Log.d("Stadshart Woerden ","Request URL : "+strUrl);
        Log.d("Stadshart Woerden ","Request Parameters : "+alstNameValuePair.toString());
        InputStream mInputStream = null;
        try {


            HttpClient mHttpClient =  getNewHttpClient();

            HttpPost mHttpPost = new HttpPost(strUrl);

            if(alstNameValuePair!=null)
            { 
                //post the value you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }

            //get the value from the server side as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();

          } 
          catch (Exception e) {
              e.printStackTrace();
          }

         String strLine = null;
         String strResult = null;

        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                  while((strLine = mBufferedReader.readLine()) != null) {
                    mStringBuilder.append(strLine + "\n");
                  }
                      strResult = mStringBuilder.toString();
                      mInputStream.close();
                }
           } 
           catch (Exception e) {
                e.printStackTrace();
            }
         Log.d("Stadshart Woerden ","Response : "+strResult);
         return strResult;
    }

2.

 private HttpClient getNewHttpClient() {

                try {               
                        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        trustStore.load(null, null);

                        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
                        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                        HttpParams params = new BasicHttpParams();
                        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

                        SchemeRegistry registry = new SchemeRegistry();
                        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                        registry.register(new Scheme("https", sf, 443));

                        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

                        return new DefaultHttpClient(ccm, params);
                    } catch (Exception e) {
                        return new DefaultHttpClient();
                    }
                }

3.

 public class MySSLSocketFactory extends SSLSocketFactory {
            SSLContext sslContext = SSLContext.getInstance("TLS");

            public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
                super(truststore);

                TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };

                sslContext.init(null, new TrustManager[] { tm }, null);
            }

            @Override
            public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
                return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
            }

            @Override
            public Socket createSocket() throws IOException {
                return sslContext.getSocketFactory().createSocket();
            }
        }
Ankitkumar Makwana
  • 3,475
  • 3
  • 19
  • 45
0

I will show you my solution. But it's not exactly what you asked. I will show you how to trust one server (Means you already know which server you are going to call, so you can download their certificate).

public static String getConnResponse(String url, String input,
            boolean isGet, boolean isJson) throws IOException {

        if (Constants.SocketFactory == null) {
            CertificateFactory cf;
            try {
                cf = CertificateFactory.getInstance("X.509");
                InputStream caInput = new URL("URL_OF_CERTIFICATE").openStream();
                Certificate ca = cf.generateCertificate(caInput);

                String keyStoreType = KeyStore.getDefaultType();
                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(null, null);
                keyStore.setCertificateEntry("ca", ca);

                // Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory
                        .getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                // Create an SSLContext that uses our TrustManager
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, tmf.getTrustManagers(), null);
                Constants.SocketFactory = context.getSocketFactory();
            } catch (CertificateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (KeyManagementException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        HttpURLConnection conn;
        if (isGet) {
            if (input == null) {
                conn = (HttpURLConnection) new URL(url).openConnection();
            } else {
                conn = (HttpURLConnection) new URL(url + "?" + input)
                .openConnection();
            }

            if (Constants.SocketFactory!=null){
                ((HttpsURLConnection) conn).setSSLSocketFactory(Constants.SocketFactory);
            }
            conn.setRequestProperty("Accept", "application/json,text/html");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Cookie", input);
        } else {
            conn = (HttpURLConnection) new URL(url).openConnection();
            if (Constants.SocketFactory!=null){
                ((HttpsURLConnection) conn).setSSLSocketFactory(Constants.SocketFactory);
            }
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", isJson ? "application/json"
                    : "application/x-www-form-urlencoded");

            OutputStream os = conn.getOutputStream();
            if(input!=null){
                os.write(input.getBytes("UTF-8"));
            }
            os.flush();
            os.close();
        }

        try {
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            is.close();
            conn.disconnect();
            return sb.toString();
        } catch (SocketException e) {// connection reset
            return null;
        } catch (Exception e) {// connection reset
            return null;
        }
    }

Constants.SocketFactory is a static variable I use to store the socket factory, so later I don't need to download it again. URL_OF_CERTIFICATE is the url of your certificate, which you can upload it to your cloud, you can also put the certificate in your asset folder, so you don't require to download it. But the downside of this solution is next time you want to talk to different server you need to build a new app. I know this is not exactly what you asked but I still decide to post it here, hopefully it will give you some clues or probably helpful to someone else have similar questions.

Ke Di
  • 345
  • 1
  • 12
  • i tried to verify the host I am checking in this site https://www.sslshopper.com/ and I got error saying "The certificate is not trusted in all web browsers. You may need to install an Intermediate/chain certificate to link it to a trusted root certificate." Is that mean I cannot download certificate from the site because there is no exist? I tried same solution above but it is not going right when I it with AndroidHttpClient. – lolliloop Jul 09 '15 at 07:14
  • I just tried to download the certificate from sslshopper.com. It works on my side, I'm using google chrome by the way. See this solution:http://superuser.com/a/97203 – Ke Di Jul 09 '15 at 07:19
  • I downloaded the certificate for your, you can see whether it's what you want: https://drive.google.com/open?id=0B7lUJZT_KrjcTFhFeXdDQW1FMVk – Ke Di Jul 09 '15 at 07:27