how to extract CN from X509Certificate in Java - without using Bouncy Castle?

做~自己de王妃 提交于 2019-12-13 01:47:00

问题


I want to preferably use only what is bundled with java security package.

From this answer, I tried:

static void parseCert(String filename) throws FileNotFoundException, CertificateException, IOException, InvalidNameException {
    FileInputStream fis = new FileInputStream(filename);
    BufferedInputStream bis = new BufferedInputStream(fis);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    while (bis.available() > 0) {
        X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
        String dn = cert.getIssuerX500Principal().getName();
        System.out.println("DN is: " + dn);
        LdapName ln = new LdapName(dn);

        for (Rdn rdn : ln.getRdns()) {
            if (rdn.getType().equalsIgnoreCase("CN")) {
                System.out.println("CN is: " + rdn.getValue());
                break;
            }
        }
    }
}

Output is

DN is: CN=LAME_IssuingCA O\=PIG C\=US

CN is: LAME_IssuingCA O=PIG C=US

Isn't this incorrect (O and C are part of CN??)


回答1:


The backslashes indicate that the second two name/value pairs aren't separate elements of the DN.



来源:https://stackoverflow.com/questions/18669041/how-to-extract-cn-from-x509certificate-in-java-without-using-bouncy-castle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!