Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCrypt
LOCAL cFileToDecrypt
LOCAL oFacIn
LOCAL nChunkSize
LOCAL nNumChunks
LOCAL oBd
LOCAL oBdDecrypted
LOCAL i

nSuccess := 0

//  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

oCrypt := CreateObject("Chilkat.Crypt2")

oCrypt:CryptAlgorithm := "aes"
oCrypt:CipherMode := "cbc"
oCrypt:KeyLength := 256

oCrypt:SetEncodedKey("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", "hex")
oCrypt:SetEncodedIV("000102030405060708090A0B0C0D0E0F", "hex")

cFileToDecrypt := "c:/temp/qa_output/hamlet.enc"
oFacIn := CreateObject("Chilkat.FileAccess")
nSuccess := oFacIn:OpenForRead(cFileToDecrypt)
IF (nSuccess != 1)
    ? "Failed to open file to be decrytped."
    oCrypt:destroy()
    oFacIn:destroy()
    RETURN
ENDIF

//  Let's decrypt in 32000 byte chunks.
nChunkSize := 32000
nNumChunks := oFacIn:GetNumBlocks(nChunkSize)

oCrypt:FirstChunk := 1
oCrypt:LastChunk := 0

oBd := CreateObject("Chilkat.BinData")
oBdDecrypted := CreateObject("Chilkat.BinData")

i := 0
DO WHILE i < nNumChunks
    i := i + 1
    IF (i == nNumChunks)
        oCrypt:LastChunk := 1
    ENDIF

    //  Read the next chunk from the file.
    //  The last chunk will be whatever amount remains in the file..
    oBd:Clear()
    oFacIn:FileReadBd(nChunkSize, oBd)

    //  Decrypt this chunk.
    oCrypt:DecryptBd(oBd)
    //  Accumulate the decrypted chunks.
    oBdDecrypted:AppendBd(oBd)

    oCrypt:FirstChunk := 0
ENDDO

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

oFacIn:FileClose()

//  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.
oBdDecrypted:WriteFile("c:/temp/qa_output/hamlet_decrypted.xml")

oCrypt:destroy()
oFacIn:destroy()
oBd:destroy()
oBdDecrypted:destroy()