通过解析 PKCS10CertificationRequest 读取请求的扩展

Reading Requested Extensions by parsing PKCS10CertificationRequest

我有一个 CSR,我正在使用 Bouncy Castle API 在 Java 中解析它,示例 CSR 如下所示:

root@serv-appliance:/usr/etc$ openssl req -text -noout -verify -in java.pem.csr
verify OK
Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: CN=INF2345, OU=DEVKI, O=Test Org, C=IN
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:b2:79:a1:ca:c8:56:83:18:e1:36:44:ed:4c:a2:
                    a2:91:f9:4d:74:af:17:91:b9:e5:c3:19:2a:be:6e:
                    54:0a:73:be:60:fd:84:a7:ac:ca:75:28:7f:2f:0f:
                    ba:0d:6c:36:22:ec:12:0f:17:59:db:1c:ae:b3:92:
                    8a:3a:fd:a7:ad
                ASN1 OID: prime256v1
        Attributes:
        Requested Extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
    Signature Algorithm: ecdsa-with-SHA1
         30:45:02:21:00:ec:c3:3c:18:94:76:89:7b:17:ae:98:e7:74:
         1f:1c:28:8a:40:4a:12:0f:55:9e:3d:7d:6d:0b:44:97:52:42:
         9c:02:20:0f:6f:a6:71:8d:cf:c3:ed:10:76:f3:da:84:f4:a8:
         3d:b4:9c:ce:6f:a9:30:cc:91:dd:c3:cc:69:56:a6:6c:d8

我能够成功解析它并读取主题通用名称。下面是我用于相同的测试代码:

    PKCS10CertificationRequest pkcsReq = parseCSR(generateRequest.getCsr());

    generateRequest.setEndEntitySubjectDn(pkcsReq.getSubject().toString());

    for (RDN att : pkcsReq.getSubject().getRDNs()) {
        for (AttributeTypeAndValue t : att.getTypesAndValues()) {
            if (t.getType().getId().equals("2.5.4.3")) {
                generateRequest.setEndEntityUserName(t.getValue().toString());
            }
            // log.debug("Type:"+t.getType().getId()+"Value:"+t.getValue().toString());
        }
    }
    for(Attribute att:pkcsReq.getAttributes()){
        log.debug("TYPE::"+att.getAttrType().getId());
        ASN1Set s = att.getAttrValues();
        Iterator<ASN1Encodable> asn1Iter = s.iterator();
        while(asn1Iter.hasNext()){
            log.debug("asn1Iter :: "+asn1Iter.next().toString());
        }
    }

但是我无法找到一种方法来读取上面证书中显示的请求扩展。

    Requested Extensions:
        X509v3 Key Usage: critical
            Digital Signature, Key Encipherment

请建议如何从 PKCS10CertificationRequest 对象中读取此信息。

由于PKCS10CertificationRequest没有getExtension或类似的方法,我看到的唯一解决方案是通过asn1结构。

我使用 openssl 1.0.1e-fips:

创建了一个示例 CSR
-----BEGIN CERTIFICATE REQUEST-----
MIICwDCCAagCAQAwWjELMAkGA1UEBhMCQlIxCzAJBgNVBAgTAlNQMRIwEAYDVQQH
EwlTYW8gUGF1bG8xDTALBgNVBAoTBHRlc3QxDDAKBgNVBAsTA29wczENMAsGA1UE
AxMEdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMjspTClIqxB
3EwJKJRTELhUowyaztgbZ/yhmM0fJISrcfWgdCK8TDO298YtUHPkGgvnb53HuMA6
BhZ33MPUxEddD+kc0orx4roIBLvu8WC746Ke3VWaQnNiEjGhVj4J8kiWG+TnYnt1
GdAcdpUY5DJ+ttLIkggavNuUdaa0Xc6nQEXZDwiXgEMwEq/rqkvTeArwhuIrUuyL
eHU4LfocXpvgKFN6o1Y4+tAwXw3gTJJxtO1F+TtBnfAvJFj8Y24tjLsvgrL+H2UH
6a2Y1OonkmOwMQXydxLssDSYrIzhS7+fvCKTqzpsz2W7RQ/sIZcouKZZgSczuScq
nF+s4GGS9ykCAwEAAaAhMB8GCSqGSIb3DQEJDjESMBAwDgYDVR0PAQH/BAQDAgWg
MA0GCSqGSIb3DQEBCwUAA4IBAQBaywDeO8cFR0yugMBmjQsvjT9NRiznxhGnfM12
cZKXONYTNEtdzgXzt6qGxWwc12nkhqvyMbhLVKyYr4JqlP4q1ZUTqYgQ8kNKAdu6
KyWHNFL+xKh57YrTxxcTI+qXAiyq9XcToyRPKNKPaLoWUVALpow12Fx0aGK2XAPm
Nij/7V79aiH2/AJDajARx8dKSL4/aZCJ+Hsjho+1h3JJrQoiBc9ugxfYa/qW1XRL
tNpfv7ftbkAiNvSwE349k7NJ7qKW2Gy9UwMUr3jC6285j73fkzJXX0bDG/HgL8AQ
kX3lOgafBlG9XTsX5eiBZdu4Ud/6OlgwczQkls5DZgRyAYGj
-----END CERTIFICATE REQUEST-----

CSR 包含与您一样的请求扩展:

    Attributes:
    Requested Extensions:
        X509v3 Key Usage: critical
            Digital Signature, Key Encipherment

我使用的代码如下(使用 bouncycastle 1.46 jdk1.6)。

请注意,如果您有更多属性,代码可能会发生变化(有很多硬编码索引和关于将要找到的对象类型的假设,因为它是针对这种特定情况的示例代码- 只有一个特定已知类型的请求扩展的 CSR)

// helper method to read the CSR
public PKCS10CertificationRequest convertPemToPKCS10CertificationRequest(String pem) throws Exception {
    PKCS10CertificationRequest csr = null;
    PEMReader reader = new PEMReader(new StringReader(pem));
    try {
        Object parsedObj = reader.readObject();

        if (parsedObj instanceof PKCS10CertificationRequest) {
            csr = (PKCS10CertificationRequest) parsedObj;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        reader.close();
    }

    return csr;
}

PKCS10CertificationRequest csr = convertPemToPKCS10CertificationRequest(csrPem);

ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
Enumeration<?> objects = attributes.getObjects();
while (objects.hasMoreElements()) {
    Object obj = (Object) objects.nextElement();
    DERSequence seq = (DERSequence) obj;
    DEREncodable objectAt = seq.getObjectAt(0);
    if (objectAt instanceof ASN1ObjectIdentifier) {
        String id = ((ASN1ObjectIdentifier) objectAt).getId();
        if ("1.2.840.113549.1.9.14".equals(id)) { // PKCS#9 ExtensionRequest
            DERSet set = (DERSet) seq.getObjectAt(1);
            // a sequence inside a sequence
            DERSequence reqExt = (DERSequence) ((DERSequence) set.getObjectAt(0)).getObjectAt(0);

            DERObjectIdentifier oid = (DERObjectIdentifier) reqExt.getObjectAt(0);
            ASN1Boolean critical = (ASN1Boolean) reqExt.getObjectAt(1);
            DEROctetString oct = (DEROctetString) reqExt.getObjectAt(2);

            System.out.println(oid.getId()); // 2.5.29.15 - key usage
            System.out.println(critical.isTrue()); // true - is critical

            KeyUsage ku = new KeyUsage(new DERBitString(oct.getOctets()));

            // in my example, the relevant part is in position 3
            // not sure if it's an issue on the way I used openssl to generate the CSR, or if it'll always be at this position
            int bits = ku.getBytes()[3] & 0xff;
            int keyUsageToCheck = KeyUsage.digitalSignature | KeyUsage.keyEncipherment;
            System.out.println((bits & keyUsageToCheck) == keyUsageToCheck); // true - it has the key usages set
        }
    }
}