Android : How to create a SSLServerSocket (TCP/IP) in Android using my own certificate. NoRouteToHostException

on Saturday, August 2, 2014


I'm writing an Android application and need to provide a SSL-secured TCP-Server using my own SSL-certificate. I've looked at all the examples I could find but even though my server code does not throw any exceptions I'm not able to connect my client to it.


Here's what I've done:

1) Certificate creation: I have a certificate (mycert.pem) and a private key (mykey.pem). As explained in this SO I've used the command-line tool 'keytool' to create a BKS-keystore from mycert.pem. An put it the /res/raw folder of my application I'm not sure what to do with the private key though, I don't need it for certificate creation do I?


2) Server-Code:



String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
KeyStore.load(context.getResouces().openRawResource(R.raw.mykeystore), "mypass".toCharArray();

String keyalg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyalg);
kmf.init(keyStore, "mypass".toCharArray());


SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
SSLServerSocket serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket(3333);

SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();

//not shown: create BufferedReader from sslSocket.getInputStream(), while-loop for incoming messages


Does that look right to you? Or have I missed something?



3) Client: I wrote a client application, that uses the same keystore, initializes a TrustManagerFactory with the keystore, creates a SSLContext passing the TrustManagerFactory as second parameter. I've read the IP-Adresse of my server application using this method and connected the client to the server by calling



clientSocket.connect(ipAdr, 3333);


The connection cannot be established. Throwing either a TimeoutException or a NoRouteToHostFoundException. Both devices are connected to the same network. No firewall. Communication between client- and server-application without using SSL and my certificate works fine. I've just wanted to make sure that my server implementation is correct and is not causing the error.


Thanks in advance for any help and input.


0 comments:

Post a Comment