Lua
Lua
Streaming Encryption by Encrypting in Chunks
See more Encryption Examples
Encrypt data in chunks.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires 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 = 128
crypt:set_encoded_key("000102030405060708090A0B0C0D0E0F", "hex")
crypt:set_encoded_iv("000102030405060708090A0B0C0D0E0F", "hex")
crypt.encoding_mode = "hex"
local txt1 = "The quick brown fox jumped over the lazy dog.\r\n"
local txt2 = "-\r\n"
local txt3 = "Done.\r\n"
local sbEncrypted = chilkat.StringBuilder.new()
-- Encrypt the 1st chunk:
-- (don't worry about feeding the data to the encryptor in
-- exact multiples of the encryption algorithm's block size.
-- Chilkat will buffer the data.)
crypt.first_chunk = true
crypt.last_chunk = false
sbEncrypted:append(crypt:encrypt_string_enc(txt1))
-- Encrypt the 2nd chunk
crypt.first_chunk = false
crypt.last_chunk = false
sbEncrypted:append(crypt:encrypt_string_enc(txt2))
-- Now encrypt N more chunks...
-- Remember -- we're doing this in CBC mode, so each call
-- to the encrypt method depends on the state from previous
-- calls...
crypt.first_chunk = false
crypt.last_chunk = false
for i = 0, 4 do
sbEncrypted:append(crypt:encrypt_string_enc(txt1))
sbEncrypted:append(crypt:encrypt_string_enc(txt2))
end
-- Now encrypt the last chunk:
crypt.first_chunk = false
crypt.last_chunk = true
sbEncrypted:append(crypt:encrypt_string_enc(txt3))
print(sbEncrypted:get_as_string())
-- Now decrypt in one call.
-- (The data we're decrypting is both the first AND last chunk.)
crypt.first_chunk = true
crypt.last_chunk = true
local decryptedText = crypt:decrypt_string_enc(sbEncrypted:get_as_string())
print(decryptedText)
-- Note: You may decrypt in N chunks by setting the FirstChunk
-- and LastChunk properties prior to calling the Decrypt* methods.