Java client certificates over HTTPS/SSL

后端 未结 8 992
攒了一身酷
攒了一身酷 2020-11-22 13:46

I am using Java 6 and am trying to create an HttpsURLConnection against a remote server, using a client certificate.
The server is using an selfsigned root

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 14:18

    While not recommended, you can also disable SSL cert validation alltogether:

    import javax.net.ssl.*;
    import java.security.SecureRandom;
    import java.security.cert.X509Certificate;
    
    public class SSLTool {
    
      public static void disableCertificateValidation() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { 
          new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() { 
              return new X509Certificate[0]; 
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {}
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }};
    
        // Ignore differences between given hostname and certificate hostname
        HostnameVerifier hv = new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) { return true; }
        };
    
        // Install the all-trusting trust manager
        try {
          SSLContext sc = SSLContext.getInstance("SSL");
          sc.init(null, trustAllCerts, new SecureRandom());
          HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
          HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (Exception e) {}
      }
    }
    

提交回复
热议问题