likejudo
likejudo

Reputation: 3735

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

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??)

Upvotes: 1

Views: 7080

Answers (1)

user207421
user207421

Reputation: 311028

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

Upvotes: 3

Related Questions