Upgrade Java socket to encrypted after issue starttls

好久不见. 提交于 2019-11-30 13:42:34

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

neoedmund

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!