Is there a way to decode CSR to String to get attributes?

1k views Asked by At

I have CSR file with content like

-----BEGIN CERTIFICATE REQUEST-----
XXXX
-----END CERTIFICATE REQUEST-----

The CSR was generated with attributes

 Attributes:
        Requested Extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Key Usage: 
                Digital Signature, Non Repudiation, Key Encipherment
            xxx: 
                ..TC200
            yyy: 
                ..1234

I tried to

guard let base64data = Data(base64Encoded: request.body) else {
            return getResponse(message: "Most likely, the request sent was in a wrong format.", code: 400)
        }

But then, base64data is nil.

Is it possible to decode the CSR, to access somehow xxx and yyy attribute in Swift? Additional information is that it's encoded with base64.

1

There are 1 answers

0
Matthias Nagel On BEST ANSWER

I assume that you are looking for decoding an ASN1 DER encoded X.509 certificate. Check out the ASN1Decoder CocoaPod.

After installation you can use the Pod like in the following example:

import ASN1Decoder

let base64CertData = "MIID..."

guard let data = Data(base64Encoded: base64CertData) else {
    return
}

do {
    let x509 = try X509Certificate(data: certData)

    let subject = x509.subjectDistinguishedName ?? ""

} catch {
    print(error)
}

Please mind to remove the -----BEGIN CERTIFICATE REQUEST----- header and -----END CERTIFICATE REQUEST----- footer.