如何在 JAVA 中获得 SSL/TLS 证书

How to get SSL/TLS certificate in JAVA

我需要做什么才能将所有 SSL/TLS 证书存储在 Windows 和 Java 的 Linux 机器中?

我会构建一个 Java 应用程序来获取存储在机器中的所有 SSL/TLS 证书,以将每个证书保存在一个文件中。

我说的是 Windows 密钥库中的 SSL/TLS 证书,您可以通过

查看这些证书

certmgr.msc(将其放在 Windows 机器的搜索栏中)

这是 Google Chrome 和 Internet Explorer 使用的那些。

已解决,这里是代码中的解决方案:

public class Main {
    private static final String CER_PATH = "**PATH_TO_SAVE_CERTIFICATES**";

    public static void main(String[] args) throws Exception {
        new File(CER_PATH).mkdirs();
        KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
        ks.load(null, null);
        Enumeration<String> en = ks.aliases();
        int n = 0;
        while (en.hasMoreElements()) {
            String aliasKey = en.nextElement();
            Certificate certificate = ks.getCertificate(aliasKey);
            saveCertificate(certificate, n++ + ". " + aliasKey);
        }
    }

    public static void saveCertificate(Certificate certificate, String name) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(CER_PATH + name + ".cer");
            fos.write(certificate.getEncoded());
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // ignore ... any significant errors should already have been
                    // reported via an IOException from the final flush.
                }
            }
        }
    }
}