In my tests I was able to use both without problems, but I could not find documentation saying wheter SSLSocketFactory.createSocket() is thread safe or not. It is possible to use the same SSLSocketFactory in mutiple threads to create SSL sockets?
My application uses a class that deals with upgrading plain 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 mutiple threads like this:
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 a SSLHandler is created. To avoid this I'm thinking in refactoring the SSLHandler 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;
}
}