Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Java to accept all certs over HTTPS

Tags:

java

https

ssl

I'm trying to get Java to accept all certs over HTTPS. This is for testing purposes. Before I was getting a cert not found error. However, after adding the following code before my code I get a HTTPS hostname wrong: should be <sub.domain.com> error. The problem is my url IS that url. How do I get around this issue? The below is the code I've added to attempt to fix the problem..

        // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
like image 905
Skizit Avatar asked Jan 19 '23 17:01

Skizit


1 Answers

You need to set the a HostNameVarifier also Ex:

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TrustAllHostNameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

}

Then

 httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier ());
like image 58
Arun P Johny Avatar answered Jan 28 '23 04:01

Arun P Johny