Checking for CA's certificate before entering a certificate?

旧城冷巷雨未停 提交于 2019-12-07 18:48:11

问题


I am inserting a client certificate into my servertruststore using following code

  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();

Now i see that certificate is entered into my truststore but the CA's certificate which signed client's certificate is not present in my truststore. So I want to know is there any way we can check whether the certificate of CA is available or not before entering a certificate into keystore?


回答1:


I guess what you have to do is to verify if the certificate has been issued by a root authority or it has been self-signed. I presume you are using the default java keystore which is cacerts. I haven't tested the code but I think this may be a solution to your problem:

  1. Code taken and modified from the following link:

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. Then you may use the following code to pass the client certificate and the Set containing all the root CAs to the verifyCertificate(X509Certificate cert, Set additionalCerts) method of the following code:

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



来源:https://stackoverflow.com/questions/10384669/checking-for-cas-certificate-before-entering-a-certificate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!