Android: HTTPS (SSL) connection using HttpsURLConnection
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 SSLContext
instead 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.
Mark Comix
I'm computer engineer. Now I'm developing for Android, Iphone, JME and Blackberry. In past I developed in Visual Fox Pro (for 6 years) and C# with MVC and ASP (for 1 year). I'm always trying to improve myself
Updated on January 09, 2020Comments
-
Mark Comix over 4 years
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?
-
Mark Comix over 12 yearsThanks, do you have some example?
-
President James K. Polk over 12 yearsI think he needs to configure the android client's truststore correctly, not the server's.
-
Nikolay Elenkov over 12 yearsNot 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 toHttpsURLConnection.setDefaultSSLSocketFactory()
. -
Mark Comix over 12 yearsThanks for the help. I will try to understand all this and make some tests. Thank you very much!
-
Mark Comix over 12 yearsI have a Question, when you said: FileInputStream in = new FileInputStream("<path to your key store>"); What file I have to use? I have "keystore" (not extension), "truststore" (not extension) and "test.cer"
-
Mark Comix over 12 yearsI'm still with some problems, but this is the right path. Really thanks
-
emboss over 12 yearsHmm- 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.
-
ivanleoncz over 7 yearsDoes 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 :).
-
Geek Guy over 5 yearsIs it safe during transport to my server without the certificate and the handshake?
-
Rainmaker about 5 years@GeekGuy nope, don't do this