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

How can I get a list of trusted root certificates in Java?(如何在 Java 中获取受信任的根证书列表?)

本文介绍了如何在 Java 中获取受信任的根证书列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在查看密钥库接口,但我希望获得 JRE 隐含的受信任根列表.

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?

推荐答案

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

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

这篇关于如何在 Java 中获取受信任的根证书列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Java 中获取受信任的根证书列表?

基础教程推荐