Sample code for 30+ languages & platforms
Lua

Decrypt File in Chunks using 256-bit AES

See more Encryption Examples

Shows how to decrypt a file chunk-by-chunk using FirstChunk/LastChunk properties and accumulate the results in memory with a Chilkat BinData object.

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.

-- This example decrypts the file previously encrypted in this example:
-- Encrypt File in Chunks using AES CBC

local crypt = chilkat.Crypt2.new()

crypt.crypt_algorithm = "aes"
crypt.cipher_mode = "cbc"
crypt.key_length = 256

crypt:set_encoded_key("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", "hex")
crypt:set_encoded_iv("000102030405060708090A0B0C0D0E0F", "hex")

local fileToDecrypt = "c:/temp/qa_output/hamlet.enc"
local facIn = chilkat.FileAccess.new()
local success = facIn:open_for_read(fileToDecrypt)
if not success then
    print("Failed to open file to be decrytped.")
    return
end

-- Let's decrypt in 32000 byte chunks.
local chunkSize = 32000
local numChunks = facIn:get_num_blocks(chunkSize)

crypt.first_chunk = true
crypt.last_chunk = false

local bd = chilkat.BinData.new()
local bdDecrypted = chilkat.BinData.new()

local i = 0
while i < numChunks do
    i = i + 1
    if i == numChunks then
        crypt.last_chunk = true
    end

    -- Read the next chunk from the file.
    -- The last chunk will be whatever amount remains in the file..
    bd:clear()
    facIn:file_read_bd(chunkSize, bd)

    -- Decrypt this chunk.
    crypt:decrypt_bd(bd)
    -- Accumulate the decrypted chunks.
    bdDecrypted:append_bd(bd)

    crypt.first_chunk = false
end

-- 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.first_chunk = true
crypt.last_chunk = true

facIn:file_close()

-- The fully decrypted file is contained in bdDecrypted.
-- You can save to a file if desired, or use the decrypted data in your application directly from bdDecrypted.
bdDecrypted:write_file("c:/temp/qa_output/hamlet_decrypted.xml")