简体   繁体   中英

How to get SSL/TLS certificate in JAVA

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.

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.
                }
            }
        }
    }
}

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