Last active
June 20, 2021 14:16
-
-
Save oneyoung/874a7f81d31b4c5a7994 to your computer and use it in GitHub Desktop.
Bypass SSL cert problem when access localhost through HTTPS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.