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

发布于 2024-09-14 10:59:18 字数 103 浏览 6 评论 0原文

我希望能够在 Java 应用程序中以编程方式访问所有受信任的根证书。

我正在查看密钥库界面,但我希望获得 JRE 隐含的可信根列表。

这在任何地方都可以访问吗?

I would like to be able to get access to all trusted root certificates programmatically in a Java app.

I was looking at the keystore interface, but I'm hoping to get the list of trusted roots that's implicit with the JRE.

Is this accessible anywhere?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

指尖微凉心微凉 2024-09-21 10:59:18

有一个示例演示如何获取一组根证书并迭代它们,名为 列出密钥库中最受信任的证书颁发机构 (CA)。这是一个稍微修改过的版本,可以打印每个证书(在 Windows Vista 上测试)。

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) {
        } 
    }
}

There's an example that shows how to get a Set of the root certificates and iterate through them called Listing the Most-Trusted Certificate Authorities (CA) in a Key Store. Here's a slightly modified version that prints out each certificate (tested on Windows Vista).

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) {
        } 
    }
}
请别遗忘我 2024-09-21 10:59:18

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

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

```

This should be more flexible using the default trust store in the system to get all certificates:

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

```

弄潮 2024-09-21 10:59:18

一个工作示例,结合了蜥蜴比尔的概念和 k_o_ 答案:

import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class JDKTrustStoreCertListing {

    public static void main(String[] args) throws Exception{
        
        String javaHome=System.getProperty("java.home");
        Path jdkCACertPath=Paths.get(javaHome, "lib", "security", "cacerts");
        
        TrustManagerFactory trustManagerFactory=TrustManagerFactory
                                                    .getInstance(TrustManagerFactory
                                                                    .getDefaultAlgorithm());
        
        FileInputStream fis=new FileInputStream(jdkCACertPath.toFile());
        String keystorePassword="changeit";
        
        KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(fis, keystorePassword.toCharArray());

        fis.close();
        
        trustManagerFactory.init(keyStore);
        
        TrustManager[] truestManagers=trustManagerFactory.getTrustManagers();
        for(TrustManager t:truestManagers)
            for(X509Certificate c:((X509TrustManager)t).getAcceptedIssuers())
                    System.out.println(c.getIssuerX500Principal());
    
    }//main closing

}//class closing

A working example, combining concept from Bill the Lizard and k_o_ answer:

import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class JDKTrustStoreCertListing {

    public static void main(String[] args) throws Exception{
        
        String javaHome=System.getProperty("java.home");
        Path jdkCACertPath=Paths.get(javaHome, "lib", "security", "cacerts");
        
        TrustManagerFactory trustManagerFactory=TrustManagerFactory
                                                    .getInstance(TrustManagerFactory
                                                                    .getDefaultAlgorithm());
        
        FileInputStream fis=new FileInputStream(jdkCACertPath.toFile());
        String keystorePassword="changeit";
        
        KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(fis, keystorePassword.toCharArray());

        fis.close();
        
        trustManagerFactory.init(keyStore);
        
        TrustManager[] truestManagers=trustManagerFactory.getTrustManagers();
        for(TrustManager t:truestManagers)
            for(X509Certificate c:((X509TrustManager)t).getAcceptedIssuers())
                    System.out.println(c.getIssuerX500Principal());
    
    }//main closing

}//class closing
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文