简体   繁体   English

Java中与平台无关的信任库路径

[英]Platform-independent trust store path in Java

I'm trying to load the system trust store in Java. 我正在尝试用Java加载系统信任库。 The problem is that my code will be shipping in a library will be used by applications for Android, Windows, linux, and OSX, and the location of the cacerts file is different on each system. 问题是我的代码将在库中发布,将被Android,Windows,Linux和OSX的应用程序使用,并且cacerts文件的位置在每个系统上都不同。

Here is my code: 这是我的代码:

        // Load the JDK's cacerts keystore file.
        String filename = System.getProperty("javax.net.ssl.trustStore");
        if (filename == null)
            filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar);
        FileInputStream is = new FileInputStream(filename);
        // Load the root certificate authorities. Despite the name, KeyStore can also hold certificates.
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        // Yes this is really the password.
        String password = "changeit";
        keystore.load(is, password.toCharArray());
        // Retrieves the most-trusted CAs from keystore.
        PKIXParameters params = new PKIXParameters(keystore);

This works fine when testing on linux, but I don't think this will work on Android for example. 在Linux上进行测试时,此方法工作正常,但例如,我认为这不适用于Android。

Is there an easy way to programatically find the location of the system trust store, or am I condemned to explicitly enumerate every possibility and hard-code the trust store path for each? 是否有一种简便的方法可以以编程方式找到系统信任库的位置,还是我应该明确列出所有可能性并对每个信任库路径进行硬编码?

a call to : 致电:

KeyStore keystore = KeyStoreUtil.getCacertsKeyStore();

will return all the System CA trusted certificates, which is a platform independent way to read the file your code. 将返回所有System CA可信证书,这是一种独立于平台的方式来读取代码文件。

Remark: your code will work if you use a null password: 备注:如果您使用空密码,您的代码将起作用:

String password = null;//"changeit";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM