Created
March 1, 2019 20:17
-
-
Save markscottwright/a8252b7a52f7ec0995b2ee3bf1ba0e86 to your computer and use it in GitHub Desktop.
How to disable TLS certificate verification in java
This file contains hidden or 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
package scratch; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.security.KeyManagementException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import javax.net.ssl.HttpsURLConnection; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
/** | |
*/ | |
public class DisableHttpSecurity { | |
public static void main(String[] args) throws IOException, | |
NoSuchAlgorithmException, | |
KeyManagementException { | |
URL url = new URL("https://example.com"); | |
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); | |
HttpsURLConnection connection = (HttpsURLConnection) url | |
.openConnection(); | |
javax.net.ssl.SSLContext context = javax.net.ssl.SSLContext | |
.getInstance("TLS"); | |
TrustManager veryTrusting = new X509TrustManager() { | |
@Override | |
public void checkClientTrusted(X509Certificate[] chain, | |
String authType) throws CertificateException { | |
} | |
@Override | |
public void checkServerTrusted(X509Certificate[] chain, | |
String authType) throws CertificateException { | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return new X509Certificate[0]; | |
} | |
}; | |
context.init(null, new TrustManager[] { veryTrusting }, null); | |
connection.setRequestMethod("GET"); | |
connection.setSSLSocketFactory(context.getSocketFactory()); | |
try (var response = connection.getInputStream()) { | |
System.out.println(new String(response.readAllBytes())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment