我正在使用以下代码根据引用here验证X509Certificate

static void verifyCertTrust(X509Certificate certificate, Set<X509Certificate> additionalCerts) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, CertPathValidatorException, InvalidAlgorithmParameterException, CertPathBuilderException{

        Set<X509Certificate> trustedRoots = new HashSet<X509Certificate>();
        Set<X509Certificate> intermediateCerts = new HashSet<X509Certificate>();

        for (X509Certificate cert : additionalCerts) {
            if(isSelfSigned(cert)){
                trustedRoots.add(cert);
            }
            else{
                intermediateCerts.add(cert);
            }
        }

        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate root : trustedRoots) {
            trustAnchors.add(new TrustAnchor(root, null));
        }

        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(certificate);


        PKIXParameters parameters = new PKIXBuilderParameters(trustAnchors, selector);
        parameters.setRevocationEnabled(false);
        CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts), "BC");
        parameters.addCertStore(intermediateCertStore);

        CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX", "BC");
        cpb.build(parameters);

    }

如果在获取BC实例的同时删除提供程序CertPathBuilder并让JVM使用默认的SUN提供程序,则此方法有效。但是,通过BC提供程序,我得到以下异常。
Exception in thread "main" java.security.cert.CertPathBuilderException: No certificate found matching targetContraints.
    at org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    at signer.GetPkcs11Key.verifyCertTrust(GetPkcs11Key.java:105)
    at signer.GetPkcs11Key.main(GetPkcs11Key.java:71)

有什么想法可以与BouncyCaSTLe提供程序一起使用吗?

最佳答案

在您的示例中,要验证的证书必须位于CertStore中,因此请添加以下内容:

 parameters.setRevocationEnabled...;
 //Add the certitificate to the cert store
 intermediateCerts.add(certificate);
 CertStore intermediateCertStore....

关于java - PKIXCertPathBuilder在Bouncy CaSTLe提供程序上失败,但在默认(SUN)提供程序下工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39438741/

10-11 14:01