MehtaiPhoneApps MehtaiPhoneApps - 2 years ago 168
iOS Question

Generate a CSR in iOS Library?

I want to see if is possible to generate a CSR (Certificate Signing Request) in iOS, and if there is a library for it. I want to generate a request, sign it with a private key from an extension, and then send the CSR request back to the server.

Is this possible, and is there a good library for it?


Answer Source

Yes, it is possible but is not simple at all because iOS do not work with standard formats for keys as you could think

I have used this library successfully to generate a CSR in PCKS#10 format with a key generated in KeyChain and encoded in DER format (binary).

func createCertificationRequest(keyId: String, C: String?, CN: String?, O:String?, SERIALNAME:String? ) -> String {

        //Replace this with your mechanism to get the private and public key
        let publicKey = loadKeyStringFromKeyChainAsNSData(keyId)
        let privateKey = loadKeySecKeyFromKeyChain(keyId)

        //SCCSR from ios-csr library
        let sccsr : SCCSR = SCCSR()

        sccsr.commonName = CN;
        sccsr.organizationName = O;
        sccsr.countryName = C;

        //    // aditional data you can set
        //    sccsr.countryName = @"";
        //    sccsr.organizationalUnitName = @"";
        //    sccsr.subjectDER = nil;
        //    //
        let certificateRequest =, privateKey: privateKey)
        let certificateRequestB64 = certificateRequest.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())

        let certificateRequestPEM =
            "-----BEGIN CERTIFICATE REQUEST-----\\n" + certificateRequestB64 + "\\n-----END CERTIFICATE REQUEST-----\\n"

        return certificateRequestPEM


After this, you can send the CSR to server in DER (format) or encode in PEM format (base64) depending of the capabilities of your serv

I guess you are missed the final step, returning the X509 from server to device to be stored

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download