Skip to content

Instantly share code, notes, and snippets.

@kenshin579
Last active October 24, 2019 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenshin579/269d9d63afdd3f9ad9b31d3737a24949 to your computer and use it in GitHub Desktop.
Save kenshin579/269d9d63afdd3f9ad9b31d3737a24949 to your computer and use it in GitHub Desktop.
public class DisableSSLCertificateCheckRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
disableCertificateCheck();
base.evaluate();
}
};
}
/**
* javax.net.ssl.SSLHandshakeException: 수동으로 certificate을 import해야 하는데,
* 한번 하고나도 몇주 지나면 다시 예외가 발생해서 코드상에서 disable 시키도록 함
* <p>
* https://stackoverflow.com/questions/4663147/is-there-a-java-setting-for-disabling-certificate-validation
*/
private void disableCertificateCheck() {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
}
}
@Slf4j
public class DisableSSLCertificateCheckRuleTest {
@ClassRule
public static DisableSSLCertificateCheckRule disableSSLRule = new DisableSSLCertificateCheckRule();
final String SSL_API_URL = "https://api.bcovlive.io";
@Test
public void test_after_import_certificate() {
Assertions.assertThatCode(this::connectHttps).doesNotThrowAnyException();
}
private void connectHttps() {
try {
URL u = new URL(SSL_API_URL);
u.openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment