Sample code for 30+ languages & platforms
Zig

Encrypt Already Existing Zip

See more Zip Examples

To encrypt an already existing non-encrypted .zip, the application must open the .zip, set the encryption related properties, and then re-write.

Chilkat Zig Downloads

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

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const zip = try chilkat.Zip.init();
    defer zip.deinit();

    // Open an unencrypted .zip
    zip.openZip("qa_data/zips/test.zip") catch {
        std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
        return;
    };

    // Unzip to a temp directory.
    const num_files_unzipped = zip.unzip("qa_output/tmp");
    if (num_files_unzipped < 0) {
        std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
        return;
    }

    // Clear the zip object.
    zip.newZip("qa_output/aesTest.zip") catch {};

    // Indicate that 128-bit AES encryption is to be used when writing the .zip
    zip.setEncryption(4);
    zip.setEncryptKeyLength(128);

    // Set the password.
    zip.setEncryptPassword("secret");

    // Append the files.
    zip.setAppendFromDir("qa_output/tmp");
    zip.appendFiles("*.*", true) catch {
        std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
        return;
    };

    // Write the .zip and close it.
    zip.writeZipAndClose() catch {
        std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Success.\n", .{});
}