Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.99+

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.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local compress = chilkat.Compression.new()
compress.algorithm = "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.
local json = chilkat.JsonObject.new()
json:update_string("cryptAlgorithm", "aes")
json:update_string("cipherMode", "cbc")
json:update_int("keyLength", 128)
json:update_int("paddingScheme", 0)
json:update_string("encodedIV", "000102030405060708090A0B0C0D0E0F")
json:update_string("encodedKey", "000102030405060708090A0B0C0D0E0F")

-- Do file-to-file compression+encryption in a single call.
local inPath = "qa_data/largeFile.dat"
local outPath = "c:/temp/qa_output/compressed_encrypted.dat"
local success = compress:compress_encrypt_file(json, inPath, outPath)
if not success then
    print(compress.last_error_text)
    return
end

-- We can do file-to-file decrypt/decompress like this:
local inPath2 = outPath
local outPath2 = "c:/temp/qa_output/restored.dat"
success = compress:decrypt_decompress_file(json, inPath2, outPath2)
if not success then
    print(compress.last_error_text)
    return
end

-- Note: The above decrypt + decompress is the equivalent of doing the same in these two steps:
local crypt = chilkat.Crypt2.new()
crypt.crypt_algorithm = "aes"
crypt.cipher_mode = "cbc"
crypt.key_length = 128
crypt.padding_scheme = 0
crypt:set_encoded_iv("000102030405060708090A0B0C0D0E0F", "hex")
crypt:set_encoded_key("000102030405060708090A0B0C0D0E0F", "hex")

local decryptedPath = "c:/temp/qa_output/decrypted.dat"
success = crypt:ck_decrypt_file(inPath2, decryptedPath)
if not success then
    print(crypt.last_error_text)
    return
end

local outPath3 = "c:/temp/qa_output/restored_in_two_steps.dat"
success = compress:decompress_file(decryptedPath, outPath3)
if not success then
    print(compress.last_error_text)
    return
end

print("Success.")