Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the SSL with multi entity on android

Tags:

android

php

ssl

Here is the code how I use appache to POST the data to a web URL. The main logic of the app to interact with the backend is , posting the data to a URL(PHP) , and that PHP runs the logic to work with the Database etc......

So, I would like to know how to implement the SSL on it? or I just need to change the PHP program , and the android side POST to a web site that start with "https" instead of "http"? Thanks

protected class FormHandler extends AsyncTask<Object, Void, JSONObject> {
        private FormListener listener;
        private ProgressDialog pd;

        public FormHandler() {
            pd = ProgressDialog.show(ctx,"", ctx.getResources().getString(R.string.loading),true);
        }

        @Override
        protected JSONObject doInBackground(Object... params) {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            listener = (FormListener) params[0];

            // Wordpress default parameter
            builder.addTextBody("_wpcf7", "610");
            builder.addTextBody("_wpcf7_version", "3.7.2");
            builder.addTextBody("_wpcf7_locale", "en_US");
            builder.addTextBody("_wpcf7_unit_tag", "wpcf7-f610-p611-o1");
            builder.addTextBody("_wpnonce", "4ddf1f1d07");
            builder.addPart("your-firstname", new StringBody((String) params[1], ContentType.create("text/plain", Consts.UTF_8)));
            builder.addPart("your-lastname", new StringBody((String) params[2], ContentType.create("text/plain", Consts.UTF_8)));
            builder.addPart("your-email", new StringBody((String) params[3], ContentType.create("text/plain", Consts.UTF_8)));
            builder.addPart("your-question", new StringBody((String) params[4], ContentType.create("text/plain", Consts.UTF_8)));
            builder.addPart("your-details", new StringBody((String) params[5], ContentType.create("text/plain", Consts.UTF_8)));
            builder.addTextBody("_wpcf7_is_ajax_call", "1");

            // Set timeout (1 minute)
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, Constant.uploadTimeout);
            HttpConnectionParams.setSoTimeout(httpParameters, Constant.uploadTimeout);

            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpPost post = new HttpPost(Constant.formURL);
            HttpEntity entity = builder.build();
            post.setEntity(entity);

            try {
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder strBuild = new StringBuilder();

                for (String line = null; (line = reader.readLine()) != null;) {
                    strBuild.append(line).append("\n");
                }

                String result = strBuild.toString().replace("<textarea>", "").replace("</textarea>", "");

                JSONTokener tokener = new JSONTokener(result);

                if (tokener != null)
                    return (new JSONObject(tokener));

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            if(pd != null) {
                pd.dismiss();
            }
            if(result != null)  {
                try {
                    if (result.getString("mailSent").equals("true"))
                        listener.submitComplete();
                    else
                        listener.submitFailure();
                } catch (JSONException e) {
                    listener.submitFailure();
                }
            } else {
                Utility.showErrorDialog(ctx, getResources().getString(R.string.sys_info), getResources().getString(R.string.err_submit), getResources().getString(R.string.close));
            }
        }
    }
like image 922
user782104 Avatar asked May 19 '14 01:05

user782104


3 Answers

Hey you can Implement SSL like below...

       private HttpResponse getResponse(HttpPost request) {
    try {
        BasicHttpParams httpParams = new BasicHttpParams();

        ConnManagerParams.setTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setTcpNoDelay(httpParams, true);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

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

        SSLSocketFactory socketFactory = new CustomSSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("https", socketFactory, Integer.parseInt(Constants.PORT_NUMBER)));
        ThreadSafeClientConnManager cManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

        HttpClient httpClient = new DefaultHttpClient(cManager, httpParams);
        return httpClient.execute(request);
    } catch (Exception e) {
        if (Constants.DEBUG) {
            Log.e(TAG, "", e);
        }
    }
    return null;
}

now CustomSSlSocketFactory.java

    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;

    import org.apache.http.conn.ssl.SSLSocketFactory;

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

public CustomSSLSocketFactory(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();
}

}

like image 169
Toppers Avatar answered Nov 14 '22 04:11

Toppers


What is your purpose of using ssl? There are different use cases:

  • SSL merely as a secure communication channel
  • SSL to verify that you are talking to the right server
  • SSL to let the server verify that the connection was made from the app

For the first two you do as you proposed, but for the last one you need a cert in the app which the webserver then can verify.

like image 25
Benjamin Hammer Nørgaard Avatar answered Nov 14 '22 04:11

Benjamin Hammer Nørgaard


// Http Client with SSL factory

public 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();
 }
}

// Post request for multi part entity

public void postRequest(){

    DefaultHttpClient httpClient = new getNewHttpClient();
    HttpPost postRequest = new HttpPost(url);
    String auth = "USER_NAME" + ":" + "PASSWORD";
    byte[] bytes = auth.getBytes();
    postRequest.setHeader("Authorization", "Basic " + new String(Base64.encodeBytes(bytes)));

    try {
        MultipartEntity mpC = new MultipartEntity();
        FileBody fb = new FileBody(message);
        StringBody sbPicID = new StringBody(fb.getFilename());
        mpC.addPart("name", sbPicID);
        mpC.addPart("file", fb);
        postRequest.setEntity(mpC);
        HttpResponse res;
        res = httpClient.execute(postRequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String resPictureId = "";
        resPictureId = rd.readLine();

        Session.put("PICTURE_"+position, resPictureId);
        res.getEntity().getContent().close();
    }catch (Exception e) {
        // TODO: handle exception
    }

}

// SSL factory class

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();
    }

}
like image 1
Usman Afzal Avatar answered Nov 14 '22 05:11

Usman Afzal