How can I get a list of trusted root certificates in Java?

Viewed 55098

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

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?

3 Answers

This should be more flexible using the default trust store in the system to get all certificates:

TrustManagerFactory trustManagerFactory =
   TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
List<Certificate> x509Certificates = new ArrayList<>();
trustManagerFactory.init((KeyStore)null);                 
Arrays.asList(trustManagerFactory.getTrustManagers()).stream().forEach(t -> {
                    x509Certificates.addAll(Arrays.asList(((X509TrustManager)t).getAcceptedIssuers()));
                });

```

A working example, combining concept from Bill the Lizard and k_o_ answer:

import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class JDKTrustStoreCertListing {

    public static void main(String[] args) throws Exception{
        
        String javaHome=System.getProperty("java.home");
        Path jdkCACertPath=Paths.get(javaHome, "lib", "security", "cacerts");
        
        TrustManagerFactory trustManagerFactory=TrustManagerFactory
                                                    .getInstance(TrustManagerFactory
                                                                    .getDefaultAlgorithm());
        
        FileInputStream fis=new FileInputStream(jdkCACertPath.toFile());
        String keystorePassword="changeit";
        
        KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(fis, keystorePassword.toCharArray());

        fis.close();
        
        trustManagerFactory.init(keyStore);
        
        TrustManager[] truestManagers=trustManagerFactory.getTrustManagers();
        for(TrustManager t:truestManagers)
            for(X509Certificate c:((X509TrustManager)t).getAcceptedIssuers())
                    System.out.println(c.getIssuerX500Principal());
    
    }//main closing

}//class closing
Related