Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

前端 未结 23 1522
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:44

I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:09

    There is a lot of way to solve this...

    One way is set the TrustStore certificates in a keystore file and put it in the path of the application, and set these system properties in the main method:

    public static void main(String[] args) {
      System.setProperty("javax.net.ssl.trustStore", "trust-store.jks");
      System.setProperty("javax.net.ssl.trustStorePassword", "TrustStore");
      ...
    }
    

    Other way is place the keystore as resource file inside the project jar file and load it:

    public static SSLContext createSSLContext(String resourcePath, String pass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
      // initialise the keystore
      final char[] password = pass.toCharArray();
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(ThisClass.class.getResourceAsStream(resourcePath
      ), password);
    
      // Setup the key manager factory.
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, password);
    
      // Setup the trust manager factory.
      TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
      tmf.init(ks);
    
      SSLContext sslc = SSLContext.getInstance("TLS");
      sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
      return sslc;
    }
    
    public static void main(String[] args) {
      SSLContext.setDefault(
        createSSLContext("/trust-store.jks", "TrustStore"));
      ...
    }
    

    In windows you can try this solution too: https://stackoverflow.com/a/59056537/980442


    I created the keystore file from a Certificate authority CA .crt file in this way:

    keytool -import -alias ca -keystore trust-store.jks -storepass TrustStore -trustcacerts -file ca.crt
    

    FYI: https://docs.oracle.com/javadb/10.8.3.0/adminguide/cadminsslclient.html

提交回复
热议问题