Created
June 29, 2016 04:18
-
-
Save hendrawd/fee5cfa2251c7072c6c82812e17fb147 to your computer and use it in GitHub Desktop.
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
import java.security.KeyManagementException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
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; | |
/** | |
* @author hendrawd on 6/29/16 | |
*/ | |
public class HttpsTrustManager implements X509TrustManager { | |
private static TrustManager[] trustManagers; | |
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{}; | |
@Override | |
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) | |
throws java.security.cert.CertificateException { | |
} | |
@Override | |
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) | |
throws java.security.cert.CertificateException { | |
} | |
public boolean isClientTrusted(X509Certificate[] chain) { | |
return true; | |
} | |
public boolean isServerTrusted(X509Certificate[] chain) { | |
return true; | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return _AcceptedIssuers; | |
} | |
/** | |
* it's not safe for production phase, because it will allow all SSL certificate | |
* although the SSL certificate is not valid | |
*/ | |
public static void allowAllSSL() { | |
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { | |
@Override | |
public boolean verify(String arg0, SSLSession arg1) { | |
return true; | |
} | |
}); | |
SSLContext context = null; | |
if (trustManagers == null) { | |
trustManagers = new TrustManager[]{new HttpsTrustManager()}; | |
} | |
try { | |
context = SSLContext.getInstance("TLS"); | |
context.init(null, trustManagers, new SecureRandom()); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (KeyManagementException e) { | |
e.printStackTrace(); | |
} | |
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment