java 如何在java中禁用证书验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13105707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:30:21  来源:igfitidea点击:

How to disable certificate validation in java

javasslnetwork-programmingcertificatessl-certificate

提问by Jury A

I need to disable Java certificate validation for testing only. So I understand the risk. I used the following tutorial: http://www.rgagnon.com/javadetails/java-fix-certificate-problem-in-HTTPS.html

我只需要为测试禁用 Java 证书验证。所以我理解风险。我使用了以下教程:http: //www.rgagnon.com/javadetails/java-fix-certificate-problem-in-HTTPS.html

So the code is:

所以代码是:

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

public class Cert {
  public static void main(String[] args) throws Exception {
    /*
     *  fix for
     *    Exception in thread "main" 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
     */
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }

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

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

       }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
          return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
     * end of the fix
     */

    URL url = new URL("https://www.nakov.com:2083/");
    URLConnection con = url.openConnection();
    Reader reader = new InputStreamReader(con.getInputStream());
    while (true) {
      int ch = reader.read();
      if (ch==-1) {
        break;
      }
      System.out.print((char)ch);
    }
      }
    }

I still get the following error. Can any body help ?

我仍然收到以下错误。任何身体都可以帮助吗?

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.nakov.com:2083/
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1615)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at MainProject.Cert.main(Cert.java:56)

回答by meriton

The "fix" and the exception appear unrelated: The fix disables verification of the server's certificate by the client while the exception indicates that the server deemed the client not authorized to access that URL.

“修复”和异常似乎无关:修复禁用客户端对服务器证书的验证,而异常表明服务器认为客户端无权访问该 URL。

回答by user207421

This won't fix the problem. The 401 was transmitted over HTTPS and SSL, so the certificates are working perfectly.

这不会解决问题。401 是通过 HTTPS 和 SSL 传输的,因此证书运行良好。

In any case I strongly recommend you don't do this. You don't want different code executing in test and production. There is a strong risk the test code will leak into production and compromise security. And there is no point in testing insecure code.

无论如何,我强烈建议您不要这样做。您不希望在测试和生产中执行不同的代码。测试代码很可能会泄漏到生产环境中并危及安全。测试不安全的代码毫无意义。

回答by Hiro2k

Don't bother disabling it in your code, you can just add the certificate to your testing machines truststore and be 100% sure you don't ship a build with the check disabled.

不要费心在您的代码中禁用它,您只需将证书添加到您的测试机器信任库中,并 100% 确保您不会在禁用检查的情况下发布构建。

回答by Eric Darchis

As mentioned by others, the error 401 means that you really established the SSL connection, sent your request and were served back this 401 error. So your SSL code is fine.

正如其他人所提到的,错误 401 意味着您确实建立了 SSL 连接,发送了您的请求并收到了此 401 错误。所以你的 SSL 代码没问题。

When you open this page in the browser, are you getting a username/password prompt ? Maybe auto-login ? If this is the case, I would say that your code is missing this basic authentication or similar.

当您在浏览器中打开此页面时,您是否收到用户名/密码提示?也许自动登录?如果是这种情况,我会说您的代码缺少此基本身份验证或类似内容。