简体   繁体   中英

Platform-independent trust store path in Java

I'm trying to load the system trust store in 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.

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.

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.

Remark: your code will work if you use a null password:

String password = null;//"changeit";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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