在输入证书之前检查CA的证书?

时间:2012-04-30 13:40:23

标签: java certificate keystore

我使用以下代码

将客户端证书插入我的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的证书是否可用?

1 个答案:

答案 0 :(得分:3)

我想你要做的就是验证证书是由root权限颁发还是已经自签名。我假设你使用的是默认的java密钥库,它是cacerts。 我没有测试过代码,但我认为这可能是您问题的解决方案:

  1. 从以下链接获取并修改代码:
  2. How can I get a list of trusted root certificates in 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)方法:
    2. http://www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-chain-and-verify-clr-with-bouncy-castle/