代码之家  ›  专栏  ›  技术社区  ›  Shawn D.

如何在Java中获得受信任的根证书列表?

  •  29
  • Shawn D.  · 技术社区  · 14 年前

    我正在查看keystore接口,但我希望得到JRE隐含的可信根的列表。

    这有什么地方可以去吗?

    2 回复  |  直到 14 年前
        1
  •  41
  •   Bill the Lizard Hacknightly    6 年前

    下面有一个示例演示了如何获取一组根证书并对它们进行迭代 Listing the Most-Trusted Certificate Authorities (CA) in a Key Store

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.PKIXParameters;
    import java.security.cert.TrustAnchor;
    import java.security.cert.X509Certificate;
    import java.util.Iterator;
    
    
    public class Main {
    
        public static void main(String[] args) {
            try {
                // Load the JDK's cacerts keystore file
                String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar);
                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();
                    System.out.println(cert);
                }
            } catch (CertificateException e) {
            } catch (KeyStoreException e) {
            } catch (NoSuchAlgorithmException e) {
            } catch (InvalidAlgorithmParameterException e) {
            } catch (IOException e) {
            } 
        }
    }
    
        2
  •  16
  •   k_o_    8 年前

    使用系统中的默认信任存储来获取所有证书应该更加灵活:

    TrustManagerFactory trustManagerFactory =
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    List<Certificate> x509Certificates = new ArrayList<>();
    trustManagerFactory.init((KeyStore)null);                 
    Arrays.asList(trustManagerFactory.getTrustManagers()).stream().forEach(t -> {
                        x509Certificates.addAll(Arrays.asList(((X509TrustManager)t).getAcceptedIssuers()));
                    });
    

    ```