Sample code for 30+ languages & platforms
Zig

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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main() !void {
    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const crypt = try chilkat.Crypt2.init();
    defer crypt.deinit();

    crypt.setCryptAlgorithm("aes");
    crypt.setCipherMode("cbc");
    crypt.setKeyLength(256);

    crypt.setEncodedKey("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", "hex");
    crypt.setEncodedIV("000102030405060708090A0B0C0D0E0F", "hex");

    const file_to_encrypt = "qa_data/hamlet.xml";
    const fac_in = try chilkat.FileAccess.init();
    defer fac_in.deinit();
    fac_in.openForRead(file_to_encrypt) catch {
        std.debug.print("Failed to open file that is to be encrytped.\n", .{});
        return;
    };

    const output_encrypted_file = "c:/temp/qa_output/hamlet.enc";
    const fac_out_enc = try chilkat.FileAccess.init();
    defer fac_out_enc.deinit();
    fac_out_enc.openForWrite(output_encrypted_file) catch {
        std.debug.print("Failed to encrypted output file.\n", .{});
        return;
    };

    // Let's encrypt in 10000 byte chunks.
    const chunk_size = 10000;
    const num_chunks = fac_in.getNumBlocks(chunk_size);

    crypt.setFirstChunk(true);
    crypt.setLastChunk(false);

    const bd = try chilkat.BinData.init();
    defer bd.deinit();

    var i: i32 = 0;
    while (i < num_chunks) {
        i = i + 1;
        if (i == num_chunks) {
            crypt.setLastChunk(true);
        }

        // Read the next chunk from the file.
        // The last chunk will be whatever amount remains in the file..
        bd.clear() catch {};
        fac_in.fileReadBd(chunk_size, bd) catch {};

        // Encrypt.
        crypt.encryptBd(bd) catch {};

        // Write the encrypted chunk to the output file.
        fac_out_enc.fileWriteBd(bd, 0, 0) catch {};

        crypt.setFirstChunk(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.setFirstChunk(true);
    crypt.setLastChunk(true);

    fac_in.fileClose();
    fac_out_enc.fileClose();

    // Decrypt the encrypted output file in a single call using CBC mode:
    const decrypted_file = "qa_output/hamlet_dec.xml";
    try crypt.ckDecryptFile(output_encrypted_file, decrypted_file);
    // Assume success for the example..

    // Compare the contents of the decrypted file with the original file:
    const b_same = fac_in.fileContentsEqual(file_to_encrypt, decrypted_file);
    std.debug.print("bSame = {}\n", .{b_same});
}