Sample code for 30+ languages & platforms
Swift

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

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.

    let pem = CkoPem()!

    // No password is required.  Pass an empty password string..
    var noPassword: String? = ""
    success = pem.loadFile(path: "qa_data/csr/csr2.pem", password: noPassword)
    if success != true {
        print("\(pem.lastErrorText!)")
        return
    }

    var strBase64: String? = pem.getEncodedItem(itemType: "csr", itemSubType: "", encoding: "base64", index: 0)

    let asn = CkoAsn()!
    success = asn.loadEncoded(asnContent: strBase64, encoding: "base64")
    if success != true {
        print("\(asn.lastErrorText!)")
        return
    }

    // Convert the ASN.1 to XML.
    let xml = CkoXml()!
    success = xml.load(xmlData: asn.asnToXml())
    print("\(xml.getXml()!)")
    print("----")

    var strModulusHex: String? = xml.getChildContent(tagPath: "bits")
    print("strModulusHex = \(strModulusHex!)")
    print("----")

    // We need the modulus as base64.
    let bd = CkoBinData()!
    bd.appendEncoded(encData: strModulusHex, encoding: "hex")
    var modulus64: String? = bd.getEncoded(encoding: "base64")
    print("modulus64 = \(modulus64!)")
    print("----")

    // Build the XML for the public key.
    let xmlPubKey = CkoXml()!
    xmlPubKey.tag = "RSAPublicKey"
    xmlPubKey.updateChildContent(tagPath: "Modulus", value: modulus64)
    // The RSA exponent will always be decimal 65537 (base64 = AQAB)
    xmlPubKey.updateChildContent(tagPath: "Exponent", value: "AQAB")

    print("RSA public key as XML:")
    print("\(xmlPubKey.getXml()!)")
    print("----")

    // Load the XML into a Chilkat public key object.
    let pubkey = CkoPublicKey()!
    success = pubkey.load(fromString: xmlPubKey.getXml())
    if success != true {
        print("\(pubkey.lastErrorText!)")
        return
    }

    // Show the public key as PEM.
    var preferPkcs1: Bool = true
    print("\(pubkey.getPem(preferPkcs1: preferPkcs1)!)")

}