Search code examples
javasslcertificatex509certificatebouncycastle

Java verify certificate againt issuer certificate


let's say I have a Root CA -> Intermediate CA -> leaf certificate. I need to verify the leaf certificate by the following code snipe:

    /**
     * Attempts to build a certification chain for given certificate and to
     * verify it. Relies on a set of root CA certificates (trust anchors) and a
     * set of intermediate certificates (to be used as part of the chain).
     *
     * @param cert              - certificate for validation
     * @param trustAnchors      - set of trust anchors
     * @param intermediateCerts - set of intermediate certificates
     * @param signDate          the date when the signing took place
     * @return the certification chain (if verification is successful)
     * @throws GeneralSecurityException - if the verification is not successful
     *                                  (e.g. certification path cannot be built or some certificate in the chain
     *                                  is expired)
     */
    private static PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, Set<TrustAnchor> trustAnchors,
                                                               Set<X509Certificate> intermediateCerts, Date signDate) throws GeneralSecurityException {
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(cert);
        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
        // Disable CRL checks (this is done manually as additional step)
        pkixParams.setRevocationEnabled(false);
        pkixParams.setPolicyQualifiersRejected(false);
        pkixParams.setDate(signDate);
        // Specify a list of intermediate certificates
        CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts));
        pkixParams.addCertStore(intermediateCertStore);
        // Build and verify the certification chain
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        return (PKIXCertPathBuilderResult) builder.build(pkixParams);
    }

I can understand that the param trustAnchors is my Root CA, and the param intermediateCerts is my Intermediate CA. But for some reasons, the Root CA is private (my customer keep it privately) and can not be passed as the trustAnchors (means trustAnchors is null/empty) here => exception occurred. It could be fixed by passing the Intermediate CA as the trustAnchors (now intermediateCerts will be null), and I could get the result. But I do not know this way is correct or not. Could someone help me to overcome the problem?


Solution

  • As @Robert said, I solved by "Then use the intermediate CA as root CA (trustAnchors). Then cert validation stops at the intermediate cert".