在 OpenJDK 11 中启用 SSL 证书吊销检查

Enable SSL certificate revocation checking in OpenJDK 11

在 Java 11 中是否有一些快速的 "declarative" 方法,而不是繁琐的手动实施,以启用检查证书是否被吊销?

我尝试使用此答案中的属性: Check X509 certificate revocation status in Spring-Security before authenticating 使用此虚拟吊销证书:https://revoked.badssl.com 但代码始终接受证书。我是不是做错了什么,或者这些属性对于 Java 11 来说不再是实际的?如果是这样,我们还有其他选择吗?

下面是我的代码:

public static void validateOnCertificateRevocation(boolean check) {
    if (check) {
        System.setProperty("com.sun.net.ssl.checkRevocation", "true");
        System.setProperty("com.sun.security.enableCRLDP", "true");

        Security.setProperty("ocsp.enable", "true");
    }

    try {
        new URL("https://revoked.badssl.com").openConnection().connect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

似乎必须在执行第一个请求之前设置这些选项。

因此,以下代码作为独立 Java 程序会抛出 CertPathValidatorException: Certificate has been revoked(在 Windows 上使用 OpenJDK 11.0.2 x64 进行测试):

public static void main(String[] args) {
    validateOnCertificateRevocation(true); // throws CertPathValidatorException
}

但是下面的代码不会导致任何errors/Exceptions:

public static void main(String[] args) {
    validateOnCertificateRevocation(false);
    validateOnCertificateRevocation(true); // nothing happens
}

您可以看到在处理完第一个请求后更改选项无效。我假设这些选项是在一些与 class.

相关的证书验证的 static { ... } 块中处理的

如果您仍想 enable/disable 对每个请求进行证书吊销检查,您可以通过实现自己的 X509TrustManager that uses CertPathValidator 来实现(为此您可以 enable/disable 证书吊销检查通过 PKIXParameters.setRevocationEnabled(boolean).

或者,还有全局启用证书吊销检查并显式处理 CertificateRevokedException 的解决方案:

private boolean checkOnCertificateRevocation;

@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
    try {
        getDefaultTrustManager().checkServerTrusted(certs, authType);
    } catch (CertificateException e) {
        if (checkOnCertificateRevocation) {
            if (getRootCause(e) instanceof CertificateRevokedException) {
                throw e;
            }
        }
    }
}