我正在尝试用 Java 加载系统信任存储。问题是我的代码将在 Android、Windows、Linux 和 OSX 的应用程序使用的库中发布,并且 cacerts 文件的位置在每个系统上都不同。
这是我的代码:
// 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);
这在 Linux 上测试时效果很好,但我认为这不适用于 Android。
是否有一种简单的方法可以以编程方式查找系统信任存储的位置,或者我是否必须明确枚举每种可能性并对每种可能性进行硬编码?
最佳答案
调用:
KeyStore keystore = KeyStoreUtil.getCacertsKeyStore();
将返回所有系统 CA 可信证书,这是一种独立于平台的方式来读取代码文件。
备注:如果您使用空密码,您的代码将正常工作:
String password = null;//"changeit";
关于java - Java 中独立于平台的信任存储路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20987236/