Sample code for 30+ languages & platforms
AutoIt

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 AutoIt Downloads

AutoIt
Local $bSuccess = False

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

$oCrypt = ObjCreate("Chilkat.Crypt2")

$oCrypt.CryptAlgorithm = "aes"
$oCrypt.CipherMode = "cbc"
$oCrypt.KeyLength = 256

$oCrypt.SetEncodedKey "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F","hex"
$oCrypt.SetEncodedIV "000102030405060708090A0B0C0D0E0F","hex"

Local $sFileToEncrypt = "qa_data/hamlet.xml"
$oFacIn = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFacIn.OpenForRead($sFileToEncrypt)
If ($bSuccess <> True) Then
    ConsoleWrite("Failed to open file that is to be encrytped." & @CRLF)
    Exit
EndIf

Local $sOutputEncryptedFile = "c:/temp/qa_output/hamlet.enc"
$oFacOutEnc = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFacOutEnc.OpenForWrite($sOutputEncryptedFile)
If ($bSuccess <> True) Then
    ConsoleWrite("Failed to encrypted output file." & @CRLF)
    Exit
EndIf

; Let's encrypt in 10000 byte chunks.
Local $iChunkSize = 10000
Local $iNumChunks = $oFacIn.GetNumBlocks($iChunkSize)

$oCrypt.FirstChunk = True
$oCrypt.LastChunk = False

$oBd = ObjCreate("Chilkat.BinData")

Local $i = 0
While $i < $iNumChunks
    $i = $i + 1
    If ($i = $iNumChunks) Then
        $oCrypt.LastChunk = True
    EndIf

    ; Read the next chunk from the file.
    ; The last chunk will be whatever amount remains in the file..
    $oBd.Clear()
    $oFacIn.FileReadBd($iChunkSize,$oBd)

    ; Encrypt.
    $oCrypt.EncryptBd($oBd)

    ; Write the encrypted chunk to the output file.
    $oFacOutEnc.FileWriteBd($oBd,0,0)

    $oCrypt.FirstChunk = False
Wend

; Make sure both FirstChunk and LastChunk are restored to True after
; encrypting or decrypting in chunks.  Otherwise subsequent encryptions/decryptions
; will produce unexpected results.
$oCrypt.FirstChunk = True
$oCrypt.LastChunk = True

$oFacIn.FileClose 
$oFacOutEnc.FileClose 

; Decrypt the encrypted output file in a single call using CBC mode:
Local $sDecryptedFile = "qa_output/hamlet_dec.xml"
$bSuccess = $oCrypt.CkDecryptFile($sOutputEncryptedFile,$sDecryptedFile)
; Assume success for the example..

; Compare the contents of the decrypted file with the original file:
Local $bSame = $oFacIn.FileContentsEqual($sFileToEncrypt,$sDecryptedFile)
ConsoleWrite("bSame = " & $bSame & @CRLF)