Sample code for 30+ languages & platforms
Swift

Generate a CSR with keyUsage, extKeyUsage, and other Extensions

See more CSR Examples

Demonstrates how to generate a CSR containing a 1.2.840.113549.1.9.14 extensionRequest with the following extensions:
  • 1.3.6.1.4.1.311.20.2 enrollCerttypeExtension
  • 2.5.29.15 keyUsage
  • 2.5.29.37 extKeyUsage
  • 2.5.29.14 subjectKeyIdentifier

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example will generate a secp256r1 ECDSA key for the CSR.
    let ecc = CkoEcc()!
    let prng = CkoPrng()!
    let privKey = CkoPrivateKey()!
    success = ecc.genKey(curveName: "secp256r1", prng: prng, privKey: privKey)
    if success == false {
        print("Failed to generate a new ECDSA private key.")
        return
    }

    let csr = CkoCsr()!

    // Add common CSR fields:
    csr.commonName = "mysubdomain.mydomain.com"
    csr.country = "GB"
    csr.state = "Yorks"
    csr.locality = "York"
    csr.company = "Internet Widgits Pty Ltd"
    csr.emailAddress = "support@mydomain.com"

    // Add the following 1.2.840.113549.1.9.14 extensionRequest
    // Note: The easiest way to know the content and format of the XML to be added is to examine
    // a pre-existing CSR with the same desired extensionRequest.  You can use Chilkat to
    // get the extensionRequest from an existing CSR. 

    // 
    // Here is a sample extension request:

    // <?xml version="1.0" encoding="utf-8"?>
    // <set>
    //     <sequence>
    //         <sequence>
    //             <oid>1.3.6.1.4.1.311.20.2</oid>
    //             <asnOctets>
    //                 <universal tag="30" constructed="0">AEUAbgBkAEUAbgB0AGkAdAB5AEMAbABpAGUAbgB0AEEAdQB0AGgAQwBlAHIAdABpAGYAaQBjAGEAdABl
    // AF8AQwBTAFIAUABhAHMAcwB0AGgAcgBvAHUAZwBoAC8AVgAx</universal>
    //             </asnOctets>
    //         </sequence>
    //         <sequence>
    //             <oid>2.5.29.15</oid>
    //             <bool>1</bool>
    //             <asnOctets>
    //                 <bits n="3">A0</bits>
    //             </asnOctets>
    //         </sequence>
    //         <sequence>
    //             <oid>2.5.29.37</oid>
    //             <asnOctets>
    //                 <sequence>
    //                     <oid>1.3.6.1.5.5.7.3.3</oid>
    //                 </sequence>
    //             </asnOctets>
    //         </sequence>
    //         <sequence>
    //             <oid>2.5.29.14</oid>
    //             <asnOctets>
    //                 <octets>MCzBMQAViXBz8IDt8LsgmJxJ4Xg=</octets>
    //             </asnOctets>
    //         </sequence>
    //     </sequence>
    // </set>

    // Use this online tool to generate code from sample XML: 
    // Generate Code to Create XML

    // A few notes:
    // The string "AEUAbgBkAEUAbgB0AGkAdAB5AEMAbABpAGUAbgB0AEEAdQB0AGgAQwBlAHIAdABpAGYAaQBjAGEAdABlAF8AQwBTAFIAUABhAHMAcwB0AGgAcgBvAHUAZwBoAC8AVgAx"
    // is the base64 encoding of the utf-16be byte representation of the string "EndEntityClientAuthCertificate_CSRPassthrough/V1"

    var s: String? = "EndEntityClientAuthCertificate_CSRPassthrough/V1"
    let bdTemp = CkoBinData()!
    bdTemp.appendString(str: s, charset: "utf-16be")
    var s_base64_utf16be: String? = bdTemp.getEncoded(encoding: "base64")
    // The string should be "AEUA....."
    print("\(s_base64_utf16be!)")

    // Here's the code to generate the above extension request.

    let xml = CkoXml()!
    xml.tag = "set"
    xml.updateChildContent(tagPath: "sequence|sequence|oid", value: "1.3.6.1.4.1.311.20.2")
    xml.updateAttrAt(tagPath: "sequence|sequence|asnOctets|universal", autoCreate: true, attrName: "tag", attrValue: "30")
    xml.updateAttrAt(tagPath: "sequence|sequence|asnOctets|universal", autoCreate: true, attrName: "constructed", attrValue: "0")
    xml.updateChildContent(tagPath: "sequence|sequence|asnOctets|universal", value: s_base64_utf16be)
    xml.updateChildContent(tagPath: "sequence|sequence[1]|oid", value: "2.5.29.15")
    xml.updateChildContent(tagPath: "sequence|sequence[1]|bool", value: "1")
    xml.updateAttrAt(tagPath: "sequence|sequence[1]|asnOctets|bits", autoCreate: true, attrName: "n", attrValue: "3")
    // A0 is hex for decimal 160.
    xml.updateChildContent(tagPath: "sequence|sequence[1]|asnOctets|bits", value: "A0")
    xml.updateChildContent(tagPath: "sequence|sequence[2]|oid", value: "2.5.29.37")
    xml.updateChildContent(tagPath: "sequence|sequence[2]|asnOctets|sequence|oid", value: "1.3.6.1.5.5.7.3.3")

    // This is the subjectKeyIdentifier extension.
    // The string "MCzBMQAViXBz8IDt8LsgmJxJ4Xg=" is base64 that decodes to 20 bytes, which is a SHA1 hash.
    // This is simply a hash of the DER of the public key.

    let pubKey = CkoPublicKey()!
    privKey.toPublicKey(pubKey: pubKey)
    let bdPubKeyDer = CkoBinData()!
    bdPubKeyDer.appendEncoded(encData: pubKey.getEncoded(preferPkcs1: true, encoding: "base64"), encoding: "base64")
    var ski: String? = bdPubKeyDer.getHash(algorithm: "sha1", encoding: "base64")

    xml.updateChildContent(tagPath: "sequence|sequence[3]|oid", value: "2.5.29.14")
    xml.updateChildContent(tagPath: "sequence|sequence[3]|asnOctets|octets", value: ski)

    // Add the extension request to the CSR
    csr.setExtensionRequest(extensionReqXml: xml)

    // Generate the CSR with the extension request
    var csrPem: String? = csr.genPem(privKey: privKey)
    if csr.lastMethodSuccess == false {
        print("\(csr.lastErrorText!)")
        return
    }

    print("\(csrPem!)")

}