8

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());
}
user1015523
  • 334
  • 2
  • 6
  • 15

2 Answers2

7

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

dfb
  • 13,133
  • 2
  • 31
  • 52
  • Can I return a certificate that I receive from a URL that I connect to? Right now, I only get the certificate errors when going to another URL on another server that is then giving the certificate errors. – user1015523 Aug 08 '12 at 05:36
  • What I've done is use a browser to pull down the cert from the site via browser (when you see the error, there should be an option in every major browser to save it to disk) and then either add it to the key store as StephenC says or use the code above from the file. The solution above may be a little less painful (albeit less flexible) because IIRC generating keystores is a bit of a chore. – dfb Aug 08 '12 at 05:42
  • 1
    If openssl is available, the certificate chain can be downloaded on the command line: openssl s_client -host www.webservicehost.com -port 443 -showcerts > output_certificate.crt – IcedDante Jun 03 '14 at 21:18
0

One possibility would be to temporarily add the problematic certificate to your JVM's key store as a trusted certificate.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216