Java阅读CSR V3扩展

时间:2019-03-31 14:32:59

标签: java certificate x509 csr

我使用工具https://certificatetools.com/newui/生成了证书签名请求(CSR),现在我想读取包括扩展名在内的所有字段。

例如,以该工具中的google.com为例,它将生成以下CSR:

Certificate Request:
    Data:
        Version: 1 (0x0)
        Subject: CN = *.google.com, C = US, ST = California, L = Mountain View, O = Google LLC
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:e3:b5:a0:d8:........
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Key Usage: critical
                Digital Signature
            X509v3 Extended Key Usage: 
                TLS Web Server Authentication
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Subject Alternative Name: 
                DNS:*.google.com, DNS:*.android.com, DNS:*.appengine.google.com, DNS:*.cloud.google.com, ...............
    Signature Algorithm: sha256WithRSAEncryption
         44:a0:41:41:88:66:......

目前,我正在通过以下方式阅读CSR:

    FileReader fileReader = new FileReader("/..../cert.csr");
    PemReader pemReader = new PemReader(fileReader);

    PKCS10CertificationRequest csr =
            new PKCS10CertificationRequest(pemReader.readPemObject().getContent());

    StringWriter writer = new StringWriter();
    PemWriter pemWriter = new PemWriter(writer);
    pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded()));
    pemWriter.flush();
    pemWriter.close();
    String csrPEM = writer.toString();

    System.out.println(csrPEM);
    System.out.println("SUBJECT: " + csr.getSubject().toString());

如何读取其余字段(例如X509v3扩展密钥用法)?

谢谢。

1 个答案:

答案 0 :(得分:0)

目前,通过这种方式,我可以在Java程序中读取CSR详细信息,效果很好。我正在阅读以获取用户uuid。

ByteArrayInputStream bais = new ByteArrayInputStream(csr);
CertificateRequest p10CertReq = new CertificateRequest(bais);
Name userDN = p10CertReq.getSubject();
String user = userDN.getRFC2253String();

iaik.pkcs.pkcs10.CertificateRequest对象公开了getAttribute方法,该方法可用于检索属性