Skip to content

Instantly share code, notes, and snippets.

@oneyoung
Last active June 20, 2021 14:16
Show Gist options
  • Save oneyoung/874a7f81d31b4c5a7994 to your computer and use it in GitHub Desktop.
Save oneyoung/874a7f81d31b4c5a7994 to your computer and use it in GitHub Desktop.
Bypass SSL cert problem when access localhost through HTTPS
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLSocketFactory;
public class BypassSSLCert {
private SSLSocketFactory mDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
private HostnameVerifier mDefaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
/* dummy TrustManager to trust all host, test only */
private static X509TrustManager getDummyTrustManager() {
return new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
}
/* by pass SSL connection error to localhost */
public void bypassLocalhostSSL(boolean enable) throws Exception {
HostnameVerifier hostnameVerifier;
SSLSocketFactory sslSocketFactory;
if (enable) {
TrustManager[] tma = new TrustManager[] {getDummyTrustManager()};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tma, new java.security.SecureRandom());
sslSocketFactory = sc.getSocketFactory();
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv = mDefaultHostnameVerifier;
if (hostname.equals("localhost")) {
return true;
} else {
return hv.verify(hostname, session);
}
}
};
} else {
sslSocketFactory = mDefaultSSLSocketFactory;
hostnameVerifier = mDefaultHostnameVerifier;
}
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}
}
@teicher
Copy link

teicher commented Aug 28, 2018

While this works for the basic use case, in a multithreaded environment setting the default hostnameVerifier will affect other threads which might not be acceptable.
Also, calling bypassLocalhostSSL(true) twice will require calling bypassLocalhostSSL(false) also twice.
I think I'd rather go with .setHostnameVerifier() on the actual HttpsUrlConnection instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment