且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java SSL / TLS忽略过期的证书? (java.security.cert.CertPathValidatorException:timestamp检查失败)

更新时间:2021-07-11 05:58:23

改变默认的SSLContext是不安全的,因为它影响整个过程。这会不加区别地降低每个连接的安全设置。它也可能不是线程安全的,虽然我不知道。

It is not safe to alter the default SSLContext since it affects the entire process. This lowers the security setting of every connection indiscriminately. It may also not be thread-safe although I am not sure.

我建议委托这样的操作到每个请求单独的进程。

I recommend delegating such operations to a separate process per-request.

String content = new HttpsNoVerify.fetch(URL.create(myURL));

com / example / HttpsNoVerify.java 的列表:

package com.example;

import org.apache.commons.io.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URL;

public class HttpsNoVerify {
    public static void main(String... args) throws Exception {
        URL url = new URL(args[0]);

        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType){}
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType){}
            }
        };

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

        IOUtils.copy(url.openStream(), System.out);
    }

    public String fetch(URL url) throws Exception {
        return new SubProcess(HttpsNoVerify.class).run(url.toString());
    }
}

com / example / SubProcess的列表。 java

package com.example;

import org.apache.commons.io.IOUtils;

import java.util.Arrays;

public class SubProcess {
    private final Class<?> classToRun;

    public SubProcess(Class<?> classToRun) {
        this.classToRun = classToRun;
    }

    public String run(String... args) throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder("java",
                "-Djava.library.path=" + System.getProperty("java.library.path"),
                "-classpath", System.getProperty("java.class.path"),
                classToRun.getCanonicalName());

        for (String arg : args) processBuilder.command().add(arg);

        processBuilder.redirectErrorStream();

        Process process = processBuilder.start();

        String output = IOUtils.toString(process.getInputStream());

        process.waitFor();

        if (process.exitValue() != 0)
            throw new IllegalStateException(
                    String.format("Running %s with %s failed", classToRun, Arrays.toString(args)));

        return output;
    }
}