Search code examples
securitysslssl-certificatejkstruststore

How to list unique Subject Alternative Names from a Java TrustStore (JKS) file


Is there any simple way (preferably from Command Line Interface) to list the unique Subject Alternative Names for all the certificates inside a Java TrustStore (JKS) file?


Solution

  • As a Java developer a small Java program can do the trick:

    public static void main(String[] args) {
        String fileName= "website_certs.jks";
        char[] password = "".toCharArray();
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(fileName), password);
            Set<Object> subjAltNames = Collections.list(ks.aliases()).stream().flatMap(alias -> {
                try {
                    return ((X509Certificate) ks.getCertificate(alias)).getSubjectAlternativeNames().stream();
                } catch (Exception e) {
                    return Stream.empty();
                }
            }).collect(Collectors.toSet());
            subjAltNames.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
    

    The only thing that is strange in your question is that a trust store usually contains root or intermediate CA certificates. But only leaf certificates installed on a web server have a subject alternative name. Therefore this code only works for trust stores that contains leaf/server certificates.