Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X509TrustManager Override without allowing ALL certs?

I am currently overriding X509TrustManager to allow all certs as a temporarily 'solution' (an unsafe one at that). I am trying to figure out how I would go about adding in so it accepts just a specific cert that I'm having issues with until a proper fix can be done (which is out of my hands at the moment). Here is the current code.

TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    @Override
    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) {
    System.out.println(e.getStackTrace());
}
like image 988
user1015523 Avatar asked Aug 08 '12 03:08

user1015523


People also ask

What happens when you disable certificate validation for JRE?

If the SSL certificate is not validates as trusted or does not match the target host, an HTTPS and other SSL encrypted connection cannot be established and all attempts will result in SSLHandshakeException or IOException.

How do I disable SSL certificate verification in REST API spring boot?

To skip or avoid the SSL check, we need to modify the default RestTemplate available with the normal Spring package. In this configuration class, we basically declare a new Bean that creates a HTTPClient with the certificate check as disabled.


1 Answers

All you need to do is return the certificate from getAcceptedIssuers. See this

 InputStream inStream = new FileInputStream("fileName-of-cert");
 CertificateFactory cf = CertificateFactory.getInstance("X.509");
 X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
 inStream.close();

and then return that in an array within the method

like image 115
dfb Avatar answered Nov 15 '22 17:11

dfb