2

What I have to do to get all the SSL/TLS certificates stored in a Windows and in a Linux machine in Java?

I would build a Java application that gets all the SSL/TLS certificates stored in the machine to save each of them in a file.

I'm talking about the SSL/TLS certificates in the Windows keystore, those that you can see through

certmgr.msc (put this in the search bar in a Windows machine)

that is those used by Google Chrome and Internet Explorer.

VanDir
  • 1,980
  • 3
  • 23
  • 41
  • Are you talking about the certificates imported into the java home keystore? – Laurentiu L. Sep 10 '15 at 14:32
  • I'm talking about the SSL/TLS certificates in the Windows keystore, those that you can see through certmgr.msc (put this in the search bar in a Windows machine), that is those used by Google Chrome and Internet Explorer. – VanDir Sep 10 '15 at 14:36
  • how about this answer: http://stackoverflow.com/questions/5476974/java-access-to-intermediate-cas-from-windows-keystores – woezelmann Sep 10 '15 at 14:55
  • I'm trying to solve my problem starting from the answer in your link, thank you. – VanDir Sep 10 '15 at 15:23

1 Answers1

3

Solved, here the solution in code:

public class Main {
    private static final String CER_PATH = "**PATH_TO_SAVE_CERTIFICATES**";

    public static void main(String[] args) throws Exception {
        new File(CER_PATH).mkdirs();
        KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
        ks.load(null, null);
        Enumeration<String> en = ks.aliases();
        int n = 0;
        while (en.hasMoreElements()) {
            String aliasKey = en.nextElement();
            Certificate certificate = ks.getCertificate(aliasKey);
            saveCertificate(certificate, n++ + ". " + aliasKey);
        }
    }

    public static void saveCertificate(Certificate certificate, String name) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(CER_PATH + name + ".cer");
            fos.write(certificate.getEncoded());
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // ignore ... any significant errors should already have been
                    // reported via an IOException from the final flush.
                }
            }
        }
    }
}
VanDir
  • 1,980
  • 3
  • 23
  • 41