Lua
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
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 fileToEncrypt = "qa_data/hamlet.xml"
local facIn = chilkat.FileAccess.new()
local success = facIn:open_for_read(fileToEncrypt)
if not success then
print("Failed to open file that is to be encrytped.")
return
end
local outputEncryptedFile = "c:/temp/qa_output/hamlet.enc"
local facOutEnc = chilkat.FileAccess.new()
success = facOutEnc:open_for_write(outputEncryptedFile)
if not success then
print("Failed to encrypted output file.")
return
end
-- Let's encrypt in 10000 byte chunks.
local chunkSize = 10000
local numChunks = facIn:get_num_blocks(chunkSize)
crypt.first_chunk = true
crypt.last_chunk = false
local bd = 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)
-- Encrypt.
crypt:encrypt_bd(bd)
-- Write the encrypted chunk to the output file.
facOutEnc:file_write_bd(bd, 0, 0)
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()
facOutEnc:file_close()
-- Decrypt the encrypted output file in a single call using CBC mode:
local decryptedFile = "qa_output/hamlet_dec.xml"
success = crypt:ck_decrypt_file(outputEncryptedFile, decryptedFile)
-- Assume success for the example..
-- Compare the contents of the decrypted file with the original file:
local bSame = facIn:file_contents_equal(fileToEncrypt, decryptedFile)
print("bSame = " .. tostring(bSame))