无法找到请求的目标PKIX路径构建的有效证书路径失败:sun.security.provider.certpath.SunCertPathBuilderException

时间:2017-11-10 07:32:51

标签: java spring security

我创建了一个自定义密钥库文件xyz.jsk,当我尝试使用这个文件时,我得到了异常

  

org.springframework.web.client.ResourceAccessException:I / O错误   POST请求:sun.security.validator.ValidatorException:PKIX   路径构建失败:   sun.security.provider.certpath.SunCertPathBuilderException:无法   找到所请求目标的有效证书路径;嵌套异常是   javax.net.ssl.SSLHandshakeException:   sun.security.validator.ValidatorException:PKIX路径构建失败:   sun.security.provider.certpath.SunCertPathBuilderException:无法   找到所请求目标的有效证书路径

   String keyStorePassword = "NEWPASSWORD";
     KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
     ClassLoader classLoader = getClass().getClassLoader();
    //  File file = new 
   File(classLoader.getResource(keyStoreFile).getFile());

     File file = new File(dir, "xyz.jks");;


    keyStore.load(new FileInputStream(file), 
    keyStorePassword.toCharArray());

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                    .build(),
            NoopHostnameVerifier.INSTANCE);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        restTemplate.setRequestFactory(httpRequestFactory);

    ((HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory())
            .setConnectTimeout(Integer.parseInt(strTimeOut));
    ResponseEntity<String> responseEntity = restTemplate.exchange(urlPath, HttpMethod.POST, entity, clazz);

1 个答案:

答案 0 :(得分:1)

用于证书解决方案的程序解决方案
请查看以下进口商品:-

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

现在功能

ClientConfig clientConfig = getClientConfig();

TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
    return null;
}

public void checkClientTrusted(X509Certificate[] certs, String authType) {
}

public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = null;
try {
    sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    // do nothing
    }

    Client client = ClientBuilder.newBuilder().withConfig(clientConfig).sslContext(sc).hostnameVerifier((s1, s2) -> true)
    .build();