Sample code for 30+ languages & platforms
Swift

Encrypt File in Chunks using AES CBC

See more Encryption Examples

Demonstrates how to use the FirstChunk/LastChunk properties to encrypt a file chunk-by-chunk.

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 = "cbc"
    crypt.keyLength = 256

    crypt.setEncodedKey(keyStr: "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", encoding: "hex")
    crypt.setEncodedIV(ivStr: "000102030405060708090A0B0C0D0E0F", encoding: "hex")

    var fileToEncrypt: String? = "qa_data/hamlet.xml"
    let facIn = CkoFileAccess()!
    success = facIn.open(forRead: fileToEncrypt)
    if success != true {
        print("Failed to open file that is to be encrytped.")
        return
    }

    var outputEncryptedFile: String? = "c:/temp/qa_output/hamlet.enc"
    let facOutEnc = CkoFileAccess()!
    success = facOutEnc.open(forWrite: outputEncryptedFile)
    if success != true {
        print("Failed to encrypted output file.")
        return
    }

    // Let's encrypt in 10000 byte chunks.
    var chunkSize: Int = 10000
    var numChunks: Int = facIn.getNumBlocks(blockSize: chunkSize).intValue

    crypt.firstChunk = true
    crypt.lastChunk = false

    let bd = CkoBinData()!

    var i: Int = 0
    while i < numChunks {
        i = i + 1
        if i == numChunks {
            crypt.lastChunk = true
        }

        // Read the next chunk from the file.
        // The last chunk will be whatever amount remains in the file..
        bd.clear()
        facIn.fileReadBd(maxNumBytes: chunkSize, binData: bd)

        // Encrypt.
        crypt.encryptBd(bd: bd)

        // Write the encrypted chunk to the output file.
        facOutEnc.fileWriteBd(binData: bd, offset: 0, numBytes: 0)

        crypt.firstChunk = false
    }

    // Make sure both FirstChunk and LastChunk are restored to true after
    // encrypting or decrypting in chunks.  Otherwise subsequent encryptions/decryptions
    // will produce unexpected results.
    crypt.firstChunk = true
    crypt.lastChunk = true

    facIn.fileClose()
    facOutEnc.fileClose()

    // Decrypt the encrypted output file in a single call using CBC mode:
    var decryptedFile: String? = "qa_output/hamlet_dec.xml"
    success = crypt.ckDecryptFile(srcFile: outputEncryptedFile, destFile: decryptedFile)
    // Assume success for the example..

    // Compare the contents of the decrypted file with the original file:
    var bSame: Bool = facIn.fileContentsEqual(path1: fileToEncrypt, path2: decryptedFile)
    print("bSame = \(bSame)")

}