16

I have 2 apps, one is a Servlet/Tomcat Server, and the other is an Android app.

I want to use HttpURLConnection to send and receive XML between both.

Code:

    private String sendPostRequest(String requeststring) {

    DataInputStream dis = null;
    StringBuffer messagebuffer = new StringBuffer();

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(this.getServerURL());

        urlConnection = (HttpURLConnection) url.openConnection();           

        urlConnection.setDoOutput(true);

        urlConnection.setRequestMethod("POST");

        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());

        out.write(requeststring.getBytes());

        out.flush();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        dis = new DataInputStream(in);

        int ch;

        long len = urlConnection.getContentLength();

        if (len != -1) {

            for (int i = 0; i < len; i++)

                if ((ch = dis.read()) != -1) {

                    messagebuffer.append((char) ch);
                }
        } else {

            while ((ch = dis.read()) != -1)
                messagebuffer.append((char) ch);
        }

        dis.close();

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        urlConnection.disconnect();
    }

    return messagebuffer.toString();
}

Now, I need to use SSL to send the XMLs for security.

First, I use Java Keytool to generate the .keystore file.

Keytool  -keygen -alias tomcat -keyalg RSA

Then I put the XML Code on server.xml file of Tomcat to use SSL

<Connector 
port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="c:/Documents and Settings/MyUser/.keystore"
keystorePass="password"
clientAuth="false" sslProtocol="TLS" 
/>

Then, I change it the HttpURLConnection for HttpsURLConnection

    private String sendPostRequest(String requeststring) {

    DataInputStream dis = null;
    StringBuffer messagebuffer = new StringBuffer();

    HttpURLConnection urlConnection = null;

    //Conexion por HTTPS
    HttpsURLConnection urlHttpsConnection = null;

    try {
        URL url = new URL(this.getServerURL());

        //urlConnection = (HttpURLConnection) url.openConnection();         

        //Si necesito usar HTTPS
        if (url.getProtocol().toLowerCase().equals("https")) {

            trustAllHosts();

            //Creo la Conexion
            urlHttpsConnection = (HttpsURLConnection) url.openConnection();

            //Seteo la verificacion para que NO verifique nada!!
            urlHttpsConnection.setHostnameVerifier(DO_NOT_VERIFY);

            //Asigno a la otra variable para usar simpre la mism
            urlConnection = urlHttpsConnection;

        } else {

            urlConnection = (HttpURLConnection) url.openConnection();
        }

//Do the same like up

and add a trustAllHosts method to Trust every server (dont check for any certificate)

private static void trustAllHosts() {

    X509TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(
                X509Certificate[] chain,
                String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(
                X509Certificate[] chain,
                String authType) throws CertificateException {
            // Oh, I am easy!
        }

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

    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

Those changes worked very good, but I don´t want to Trust every server. I want to use my keystore file to validate the connection and use SSL in the right way. I read a lot on the internet and made a lot of tests, but I can´t understand what I have to do and how to do it.

Can somebody help me?

Thank you very much

Sorry for my poor english

-------------------------UPDATE 2011/08/24-------------------------------------------------

Well, I'm still working on this. I made a new method to set the KeyStore, InputStream, etc

The method looks like this:

private static void trustIFNetServer() {

    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        KeyStore ks = KeyStore.getInstance("BKS");

        InputStream in = context.getResources().openRawResource(R.raw.mykeystore);

        String keyPassword = "password"; 

        ks.load(in, keyPassword.toCharArray());

        in.close();

        tmf.init(ks);

        TrustManager[] tms = tmf.getTrustManagers();    

        SSLContext sc = SSLContext.getInstance("TLS");

    sc.init(null, tms, new java.security.SecureRandom());

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

First I had a lot of problems with the Key and the Certificate, but now it is working (I think so)

My problem right now is a TimeOut Exception. I don´t know why it is generated. I'm think it's something with the data write, but I can't solve yet.

Any Idea?

flooose
  • 499
  • 8
  • 25
Mark Comix
  • 1,878
  • 7
  • 28
  • 44

3 Answers3

7

You need to create a trust store file for your self-signed certificate as described here. Use it on the client side to connect with your server. It doesn't really matter if you use JKS or another format, I'll assume JKS for now.

To accomplish what you have in mind you need a different TrustManager, obviously. You can use TrustManagerFactory and feed its trust settings with your newly created trust store.

TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("<path to your key store>");
ks.load(in, "password".toCharArray());
in.close();
tmf.init(ks);
TrustManager[] tms = tmf.getTrustManagers();

Use tms to init your SSLContextinstead for the new trust settings to be used for your SSL/TLS connection.

Also you should make sure that the CN part of the server TLS certificate is equal to the FQDN (fully qualified domain name) of your server, e.g. if your server base URL is 'https://www.example.com', then the CN of the certificate should be 'www.example.com'. This is needed for host name verification, a feature that prevents man-in-the-middle-attacks. You could disable this, but only when using this your connection will be really secure.

Mike
  • 741
  • 13
  • 40
emboss
  • 38,880
  • 7
  • 101
  • 108
  • I think he needs to configure the android client's truststore correctly, not the server's. – President James K. Polk Aug 20 '11 at 11:12
  • Thanks for the help. I will try to understand all this and make some tests. Thank you very much! – Mark Comix Aug 23 '11 at 12:37
  • I have a Question, when you said: FileInputStream in = new FileInputStream(""); What file I have to use? I have "keystore" (not extension), "truststore" (not extension) and "test.cer" – Mark Comix Aug 23 '11 at 15:29
  • I'm still with some problems, but this is the right path. Really thanks – Mark Comix Aug 26 '11 at 15:38
  • Hmm- I submitted a comment, but seems it didn't appear... sorry. Yes, it's the truststore file you would need to use in that situation. – emboss Aug 26 '11 at 15:44
  • Does anyone have a Gist that includes this code from @emboss ? It would be pretty nice to have something like that, specially because there isn't so much CLEAR examples about trusting self-signed certificates on Android :). – ivanleoncz Sep 16 '16 at 23:24
0

If you want to ignore all the certificate, ignore the handshake, then this works: HttpsURLConnection and intermittent connections

Community
  • 1
  • 1
Noman Arain
  • 1,172
  • 4
  • 19
  • 45
0

Create your trust store, store at as an asset and use it initialize this SocketFactory. Then use the factory instead of your own 'trust everybody' one.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
  • Thanks, do you have some example? – Mark Comix Aug 19 '11 at 18:08
  • Not a full example, but once you have loaded you trust store (which contains the server certificate), just pass it to the constructor along with the password. Then you can pass the resulting `SocketFactory` instance to `HttpsURLConnection.setDefaultSSLSocketFactory()`. – Nikolay Elenkov Aug 20 '11 at 12:15