Sample code for 30+ languages & platforms
Swift

Example: Crypt2.RandomizeIV method

Demonstrates using a random initialization vector for AES GCM encryption.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let crypt = CkoCrypt2()!

    crypt.cryptAlgorithm = "aes"
    crypt.cipherMode = "gcm"
    crypt.keyLength = 256

    var K: String? = "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F"
    var AAD: String? = "feedfacedeadbeeffeedfacedeadbeefabaddad2"
    var PT: String? = "This is the text to be AES-GCM encrypted."

    // Generate a random IV.
    crypt.randomizeIV()
    var IV: String? = crypt.getEncodedIV(encoding: "hex")

    crypt.setEncodedKey(keyStr: K, encoding: "hex")

    success = crypt.setEncodedAad(aadStr: AAD, encoding: "hex")

    // Return the encrypted bytes as base64
    crypt.encodingMode = "base64"
    crypt.charset = "utf-8"
    var cipherText: String? = crypt.encryptStringENC(str: PT)
    if crypt.lastMethodSuccess != true {
        print("\(crypt.lastErrorText!)")
        return
    }

    // Get the GCM authenticated tag computed when encrypting.
    var authTag: String? = crypt.getEncodedAuthTag(encoding: "base64")

    print("Cipher Text: \(cipherText!)")
    print("Auth Tag: \(authTag!)")

    // Let's send the IV, CipherText, and AuthTag to the decrypting party.
    // We'll send them concatenated like this: [IV || Ciphertext || AuthTag]
    // In base64 format.
    let bdEncrypted = CkoBinData()!
    bdEncrypted.appendEncoded(encData: IV, encoding: "hex")
    bdEncrypted.appendEncoded(encData: cipherText, encoding: "base64")
    bdEncrypted.appendEncoded(encData: authTag, encoding: "base64")

    var concatenatedGcmOutput: String? = bdEncrypted.getEncoded(encoding: "base64")
    print("Concatenated GCM Output: \(concatenatedGcmOutput!)")

    // Sample output so far:

    // -------------------------------------------------------------------------------------
    // Now let's GCM decrypt...
    // -------------------------------------------------------------------------------------

    let decrypt = CkoCrypt2()!

    // The values shared and agreed upon by both sides beforehand are: algorithm, cipher mode, secret key, and AAD.
    // Sometimes the IV can be a value already known and agreed upon, but in this case the encryptor sends the IV to the decryptor.
    decrypt.cryptAlgorithm = "aes"
    decrypt.cipherMode = "gcm"
    decrypt.keyLength = 256
    decrypt.setEncodedKey(keyStr: K, encoding: "hex")
    decrypt.setEncodedAad(aadStr: AAD, encoding: "hex")

    let bdFromEncryptor = CkoBinData()!
    bdFromEncryptor.appendEncoded(encData: concatenatedGcmOutput, encoding: "base64")

    var sz: Int = bdFromEncryptor.numBytes.intValue

    // Extract the parts.
    var extractedIV: String? = bdFromEncryptor.getEncodedChunk(offset: 0, numBytes: 16, encoding: "hex")
    var extractedCipherText: String? = bdFromEncryptor.getEncodedChunk(offset: 16, numBytes: sz - 32, encoding: "base64")
    var expectedAuthTag: String? = bdFromEncryptor.getEncodedChunk(offset: sz - 16, numBytes: 16, encoding: "base64")

    // Before GCM decrypting, we must set the authenticated tag to the value that is expected.
    // The decryption will fail if the resulting authenticated tag is not equal to the expected result.
    success = decrypt.setEncodedAuthTag(authTagStr: expectedAuthTag, encoding: "base64")

    // Also set the IV.
    decrypt.setEncodedIV(ivStr: extractedIV, encoding: "hex")

    // Decrypt..
    decrypt.encodingMode = "base64"
    decrypt.charset = "utf-8"
    var decryptedText: String? = decrypt.decryptStringENC(str: extractedCipherText)
    if decrypt.lastMethodSuccess != true {
        // Failed.  The resultant authenticated tag did not equal the expected authentication tag.
        print("\(decrypt.lastErrorText!)")
        return
    }

    print("Decrypted: \(decryptedText!)")

}