Are SSLContext and SSLSocketFactory createSocket safe?

In my tests, I was able to use both without problems, but I could not find the documentation saying that SSLSocketFactory.createSocket () is thread safe or not. Can I use the same SSLSocketFactory in multiple threads to create SSL sockets?

My application uses a class that is related to upgrading standard text sockets to SSL:

public class SSLHandler() {
    public Socket upgradeToSSL(Socket plainSocket) {
        SSLSocket sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManager = new TrustManager[]{
            new MyOwnTrustManager()
        };

        sslContext.init(null, trustManager, null);
        SSLSocketFactory sslsocketfactory = sslContext.getSocketFactory();

        sslSocket = (SSLSocket) sslsocketfactory.createSocket(
                    remoteSocket,
                    remoteSocket.getInetAddress().getHostAddress(),
                    remoteSocket.getPort(),
                    true);

        return sslSocket;
    }
}

The SSLHandler class is used in multiple threads, for example:

Socket plainSocket = new Socket(host, port);
//Do some stuff in plain text...

//Lets use TLS now
SSLHandler sslHandler = new SSLHandler();
sslHandler.upgradeToSSL(Socket plainSocket);

plainSocket = upgradeToSSL(plainSocket);

So, for each new thread, an SSLHandler is created. To avoid this, I am thinking of SSLHandler refactoring using the Singleton pattern:

public class SingletonSSLHandler() {
    private SSLSocket sslContext;
    private SSLSocketFactory sslSocketFactory;

    //GetInstance() and etc.

    private SingletonSSLHandler() {
        sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManager = new TrustManager[]{
            new MyOwnTrustManager()
        };

        sslContext.init(null, trustManager, null);
        sslSocketFactory = sslContext.getSocketFactory();
    }

    public static Socket upgradeToSSL(Socket plainSocket) {

        sslSocket = (SSLSocket) sslsocketfactory.createSocket(
                    remoteSocket,
                    remoteSocket.getInetAddress().getHostAddress(),
                    remoteSocket.getPort(),
                    true);

        return sslSocket;
    }
}
+4
source share

Source: https://habr.com/ru/post/1680905/


All Articles