Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrade Java socket to encrypted after issue starttls

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?

like image 690
Bijoy Avatar asked Dec 08 '11 04:12

Bijoy


2 Answers

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);
like image 148
Jan de Vos Avatar answered Sep 20 '22 00:09

Jan de Vos


@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.

like image 20
james.garriss Avatar answered Sep 23 '22 00:09

james.garriss