2

我正在使用以下代码将客户端证书插入到我的 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 的证书是否可用?

4

1 回答 1

3

我想您要做的就是验证证书是由根授权机构颁发的还是自签名的。我假设您使用的是默认的 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 的 Set 传递给以下代码的 verifyCertificate(X509Certificate cert, Set additionalCerts) 方法:

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

于 2012-04-30T14:22:04.273 回答