Update Java socket for encryption after startup

I want my application to talk to the server without encryption before releasing STARTTLS, and then update the socket, which will be encrypted after that. Can I connect to a port (e.g. 5222) and use STARTTLS to request TLS using java? If so, which Socket object should I use for this?

+8
java ssl sockets starttls
source share
3 answers

Of course. Use your SSLSocketFactory to create a socket wrapping an existing regular java.net.Socket:

SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); 
+9
source share

@ The answer was helpful (and I voted for it), but I had to tweak it a bit to make it work for me:

 SSLSocket sslSocket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); InputStream inputStream = sslSocket.getInputStream(); OutputStream outputStream = sslSocket.getOutputStream(); // reads from the socket Scanner scanner = new Scanner(inputStream); // writes to the socket OutputStream outputStream = new BufferedOutputStream(outputStream); 

Tested with Java 7 and GMail (smtp.gmail.com) on port 587.

+5
source share

An improvement is possible here: if your code is intended for the server side instead of the client side, add this and it will work fine:

 sslsocket.setUseClientMode(false); sslsocket.startHandshake(); 
+1
source share

All Articles