如何从Java中的X509Certificate中提取CN - 不使用Bouncy Castle?

时间:2013-09-07 02:20:14

标签: java certificate x509certificate

我想最好只使用与java安全包捆绑的内容。

从这answer开始,我尝试了:

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

输出

  

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

     

CN是:LAME_IssuingCA O = PIG C = US

这不正确(O和C是CN的一部分吗?)

1 个答案:

答案 0 :(得分:2)

反斜杠表示后两个名称/值对不是DN的单独元素。