检查进入证书之前,CA的证书?(Checking for CA's certificate

2019-09-16 20:55发布

我使用下面的代码插入一个客户端证书到我servertruststore

  FileInputStream fileInputStream = new FileInputStream( "c:/server.jks" );
    keyStore.load( fileInputStream, "keystore".toCharArray() );
    fileInputStream.close();
    keyStore.setCertificateEntry( alias, new X509Certificate( trustedCertificate ) );

    FileOutputStream fileOutputStream = new FileOutputStream("c:/server.jks" );
    keyStore.store( fileOutputStream, "keystore".toCharArray() );
    fileOutputStream.close();

现在我看到该证书被输入到我的信任,但该客户签署证书的CA的证书没有出现在我的信任。 所以我想知道有没有什么办法,我们可以检查CA的证书是否进入一个证书密钥存储进之前用或不?

Answer 1:

我猜你所要做的就是核实,如果该证书由根颁发机构颁发或它已经自签署。 我想你使用的是默认Java密钥是cacerts的。 我没有测试的代码,但我认为这可能是你的问题的解决方案:

  1. 从以下链接采取和修改后的代码:

我怎样才能在Java中受信任的根证书列表?

        String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar);
        Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
        FileInputStream is = new FileInputStream(filename);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "changeit";
        keystore.load(is, password.toCharArray());

        // This class retrieves the most-trusted CAs from the keystore
        PKIXParameters params = new PKIXParameters(keystore);

        // Get the set of trust anchors, which contain the most-trusted CA certificates
        Iterator it = params.getTrustAnchors().iterator();
        while( it.hasNext() ) {
            TrustAnchor ta = (TrustAnchor)it.next();
            // Get certificate
            X509Certificate cert = ta.getTrustedCert();
            additionalCerts.add(cert);
        }
  1. 然后,你可以使用以下代码来传递客户端证书和包含所有根CA向verifyCertificate(x509证书的证书,设置additionalCerts)下面的代码的方法的集:

http://www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-chain-and-verify-clr-with-bouncy-castle/



文章来源: Checking for CA's certificate before entering a certificate?