Sample code for 30+ languages & platforms
PowerBuilder

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

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Crypt
string ls_FileToDecrypt
oleobject loo_FacIn
integer li_ChunkSize
integer li_NumChunks
oleobject loo_Bd
oleobject loo_BdDecrypted
integer i

li_Success = 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

loo_Crypt = create oleobject
li_rc = loo_Crypt.ConnectToNewObject("Chilkat.Crypt2")
if li_rc < 0 then
    destroy loo_Crypt
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_Crypt.CryptAlgorithm = "aes"
loo_Crypt.CipherMode = "cbc"
loo_Crypt.KeyLength = 256

loo_Crypt.SetEncodedKey("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F","hex")
loo_Crypt.SetEncodedIV("000102030405060708090A0B0C0D0E0F","hex")

ls_FileToDecrypt = "c:/temp/qa_output/hamlet.enc"
loo_FacIn = create oleobject
li_rc = loo_FacIn.ConnectToNewObject("Chilkat.FileAccess")

li_Success = loo_FacIn.OpenForRead(ls_FileToDecrypt)
if li_Success <> 1 then
    Write-Debug "Failed to open file to be decrytped."
    destroy loo_Crypt
    destroy loo_FacIn
    return
end if

// Let's decrypt in 32000 byte chunks.
li_ChunkSize = 32000
li_NumChunks = loo_FacIn.GetNumBlocks(li_ChunkSize)

loo_Crypt.FirstChunk = 1
loo_Crypt.LastChunk = 0

loo_Bd = create oleobject
li_rc = loo_Bd.ConnectToNewObject("Chilkat.BinData")

loo_BdDecrypted = create oleobject
li_rc = loo_BdDecrypted.ConnectToNewObject("Chilkat.BinData")

i = 0
do while i < li_NumChunks
    i = i + 1
    if i = li_NumChunks then
        loo_Crypt.LastChunk = 1
    end if

    // Read the next chunk from the file.
    // The last chunk will be whatever amount remains in the file..
    loo_Bd.Clear()
    loo_FacIn.FileReadBd(li_ChunkSize,loo_Bd)

    // Decrypt this chunk.
    loo_Crypt.DecryptBd(loo_Bd)
    // Accumulate the decrypted chunks.
    loo_BdDecrypted.AppendBd(loo_Bd)

    loo_Crypt.FirstChunk = 0
loop

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

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


destroy loo_Crypt
destroy loo_FacIn
destroy loo_Bd
destroy loo_BdDecrypted