gpt4 book ai didi

java - 如何禁用特定 http 请求的证书验证?

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:32 26 4
gpt4 key购买 nike

我是 Java Spring 世界的初学者,我不知道如何处理我的情况。我必须通过 HTTPS 使用一些 API,这些 API 具有由不受信任的 CA 颁发的证书。我有一个代码:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json;charset=UTF-8");
headers.add("Accept", "*/*");
ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(url, byte[].class, headers);

当然因为证书不可信我曾经得到 Java 错误:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

所以我用代码禁用了证书验证:

public class SSLCertificateValidation {
public static void disable() {
try {
SSLContext sslc = SSLContext.getInstance("TLS");
TrustManager[] trustManagerArray = { new NullX509TrustManager() };
sslc.init(null, trustManagerArray, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
}
catch(Exception e) {
e.printStackTrace();
}
}

private static class NullX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
System.out.println();
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
System.out.println();
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}

private static class NullHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}

现在我的应用程序可以使用此 API,但另一方面,我正在使用此应用程序中的一些 AWS 服务。现在我收到 AWS 错误:

c.a.h.AmazonHttpClient - Unable to execute HTTP request: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

有什么方法可以仅针对特定 URL 禁用证书验证吗?我不知道我现在该怎么办。

PS 我知道如何将证书安装到 Java cacerts。但不幸的是,它不适合我的情况。

最佳答案

不是禁用 SSL 检查,而是尝试将证书安装到 java cacerts,这样(我假设是自签名证书)被视为受信任的证书。

获取证书的最佳方式是让服务的所有者为您提供证书,否则您应该能够很容易地从浏览器中导出证书文件。

我不会详细介绍安装证书,因为这个问题有一些很好的答案 How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

关于java - 如何禁用特定 http 请求的证书验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com