An example custom `SSLSocketFactory` is below:
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class KitKatSocketFactory extends SSLSocketFactory {
private SSLSocketFactory sslSocketFactory;
public KitKatSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
// The first `null` is the `KeyManager`, the second `null` is the `TrustManager`, and the third `null` is `SecureRandom`.
sslContext.init(null, null, null);
sslSocketFactory = sslContext.getSocketFactory();
}
private Socket disableSSLv3(Socket socket) {
if ((socket != null) && (socket instanceof SSLSocket)) {
String[] originalSocketProtocolsArray = ((SSLSocket) socket).getEnabledProtocols();
ArrayList<String> newSocketProtocolsArrayList = new ArrayList<>();
for (String originalSocketProtocolString : originalSocketProtocolsArray) {
if (!originalSocketProtocolString.contains("SSL")) {
newSocketProtocolsArrayList.add(originalSocketProtocolString);
}
}
String[] newSocketProtocolsArray = (String[]) newSocketProtocolsArrayList.toArray();
((SSLSocket) socket).setEnabledProtocols(newSocketProtocolsArray);
}
return socket;
}
@Override
public String[] getDefaultCipherSuites() {
return sslSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return sslSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(String host, int port) throws IOException {
Socket socket = sslSocketFactory.createSocket(host, port);
return disableSSLv3(socket);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
Socket socket = sslSocketFactory.createSocket(host, port);
return disableSSLv3(socket);
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
Socket socket = sslSocketFactory.createSocket(address, port, localAddress, localPort);
return disableSSLv3(socket);
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
Socket socket = sslSocketFactory.createSocket(s, host, port, autoClose);
return disableSSLv3(socket);
}
@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException {
Socket socket = sslSocketFactory.createSocket(host, port, localAddress, localPort);
return disableSSLv3(socket);
}
}