I am doing socket communication through follwing IP address it working but no i want to do communication in ssl mode but how can I change InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
to SSL.
public class TCPClient implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr,12345);
String message = "Hello from Client android emulator";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
Basically you need to use SSLSocket which is for SSL communication in Java.
When creating the SSLSocket, you first need to configure the trust store which is to verify the server certificate.
Then you need to get the SSLSocket and connect to the server and then start to do handshake with the server.
Once the handshake complete successfully, you can start to exchange application data with server normally like other plain socket connection.
A HTTPS client and HTTPS server demo in Java provides a demo on how to create SSL server and SSL client in Java. It's quite useful.
Create SSLSocket instead of Socket. Rest is the same.
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.2", 12345);
You may want to add aditional SSL properties. You have to do it ealier:
To authenticate the server, the client's trust store must contain the server's certificate. Client SSL with server authentication is enabled by the URL attribute ssl or the property ssl set to peerAuthentication. In addition, the system properties javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword need to be set.:
System.setProperty("javax.net.ssl.trustStore","clientTrustStore.key");
System.setProperty("javax.net.ssl.trustStorePassword","qwerty");
If the server does client authentication, the client will need a key pair and a client certificate:
System.setProperty("javax.net.ssl.keyStore","clientKeyStore.key");
System.setProperty("javax.net.ssl.keyStorePassword","qwerty");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With