9

I want my app to talk to the server without encryption before issuing a STARTTLS and then upgrade the socket to 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 that?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Bijoy
  • 399
  • 2
  • 7
  • 15

3 Answers3

14

Sure you can. 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);
Jan de Vos
  • 3,778
  • 1
  • 20
  • 16
7

@Jan's answer was helpful (and I voted for it), but I had to tweak it a bit to get it working 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.

james.garriss
  • 12,959
  • 7
  • 83
  • 96
1

Here's a possible improvement: If your code is for server side instead of client side, add this, and it will work fine:

sslsocket.setUseClientMode(false); 
sslsocket.startHandshake();
james.garriss
  • 12,959
  • 7
  • 83
  • 96
neoedmund
  • 561
  • 7
  • 15