簡體   English   中英

Java 驗證證書和頒發者證書

[英]Java verify certificate againt issuer certificate

假設我有一個根 CA -> 中間 CA -> 葉證書。 我需要通過以下代碼狙擊驗證葉子證書:

    /**
     * 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);
    }

我可以理解參數 trustAnchors 是我的根 CA,參數 intermediateCerts 是我的中間 CA。 但是由於某些原因,根 CA 是私有的(我的客戶將其保密)並且不能作為 trustAnchors 傳遞(意味着 trustAnchors 為空/空)=> 發生異常。 可以通過將中間 CA 作為 trustAnchors 來修復它(現在 middleCerts 將為空),我可以獲得結果。 但我不知道這種方式是否正確。 有人可以幫我解決這個問題嗎?

正如@Robert 所說,我通過“然后使用中間 CA 作為根 CA(trustAnchors)來解決。然后證書驗證在中間證書處停止”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM