Zig
Zig
Compress and Encrypt a Large File (Low and Constant Memory Footprint)
See more Compression Examples
Demonstrates how to compress and encrypt a large file such that the memory footprint remains low and constant.Note: This example requires Chilkat v9.5.0.99 or greater.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const compress = try chilkat.Compression.init();
defer compress.deinit();
compress.setAlgorithm("deflate");
// Set encryption params.
// The possible values are the same as for the corresponding properties in the Chilkat Crypt2 class/object.
// The encoded IV and Key must be specified as hex.
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.updateString("cryptAlgorithm", "aes") catch {};
json.updateString("cipherMode", "cbc") catch {};
json.updateInt("keyLength", 128) catch {};
json.updateInt("paddingScheme", 0) catch {};
json.updateString("encodedIV", "000102030405060708090A0B0C0D0E0F") catch {};
json.updateString("encodedKey", "000102030405060708090A0B0C0D0E0F") catch {};
// Do file-to-file compression+encryption in a single call.
const in_path = "qa_data/largeFile.dat";
const out_path = "c:/temp/qa_output/compressed_encrypted.dat";
compress.compressEncryptFile(json, in_path, out_path) catch {
std.debug.print("{s}\n", .{try compress.getLastErrorText(alloc)});
return;
};
// We can do file-to-file decrypt/decompress like this:
const in_path2 = out_path;
const out_path2 = "c:/temp/qa_output/restored.dat";
compress.decryptDecompressFile(json, in_path2, out_path2) catch {
std.debug.print("{s}\n", .{try compress.getLastErrorText(alloc)});
return;
};
// Note: The above decrypt + decompress is the equivalent of doing the same in these two steps:
const crypt = try chilkat.Crypt2.init();
defer crypt.deinit();
crypt.setCryptAlgorithm("aes");
crypt.setCipherMode("cbc");
crypt.setKeyLength(128);
crypt.setPaddingScheme(0);
crypt.setEncodedIV("000102030405060708090A0B0C0D0E0F", "hex");
crypt.setEncodedKey("000102030405060708090A0B0C0D0E0F", "hex");
const decrypted_path = "c:/temp/qa_output/decrypted.dat";
crypt.ckDecryptFile(in_path2, decrypted_path) catch {
std.debug.print("{s}\n", .{try crypt.getLastErrorText(alloc)});
return;
};
const out_path3 = "c:/temp/qa_output/restored_in_two_steps.dat";
compress.decompressFile(decrypted_path, out_path3) catch {
std.debug.print("{s}\n", .{try compress.getLastErrorText(alloc)});
return;
};
std.debug.print("Success.\n", .{});
}