Xbase++
Xbase++
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 Xbase++ Downloads
LOCAL nSuccess
LOCAL oCrypt
LOCAL cFileToEncrypt
LOCAL oFacIn
LOCAL cOutputEncryptedFile
LOCAL oFacOutEnc
LOCAL nChunkSize
LOCAL nNumChunks
LOCAL oBd
LOCAL i
LOCAL cDecryptedFile
LOCAL nBSame
nSuccess := 0
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
oCrypt := CreateObject("Chilkat.Crypt2")
oCrypt:CryptAlgorithm := "aes"
oCrypt:CipherMode := "cbc"
oCrypt:KeyLength := 256
oCrypt:SetEncodedKey("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", "hex")
oCrypt:SetEncodedIV("000102030405060708090A0B0C0D0E0F", "hex")
cFileToEncrypt := "qa_data/hamlet.xml"
oFacIn := CreateObject("Chilkat.FileAccess")
nSuccess := oFacIn:OpenForRead(cFileToEncrypt)
IF (nSuccess != 1)
? "Failed to open file that is to be encrytped."
oCrypt:destroy()
oFacIn:destroy()
RETURN
ENDIF
cOutputEncryptedFile := "c:/temp/qa_output/hamlet.enc"
oFacOutEnc := CreateObject("Chilkat.FileAccess")
nSuccess := oFacOutEnc:OpenForWrite(cOutputEncryptedFile)
IF (nSuccess != 1)
? "Failed to encrypted output file."
oCrypt:destroy()
oFacIn:destroy()
oFacOutEnc:destroy()
RETURN
ENDIF
// Let's encrypt in 10000 byte chunks.
nChunkSize := 10000
nNumChunks := oFacIn:GetNumBlocks(nChunkSize)
oCrypt:FirstChunk := 1
oCrypt:LastChunk := 0
oBd := 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)
// Encrypt.
oCrypt:EncryptBd(oBd)
// Write the encrypted chunk to the output file.
oFacOutEnc:FileWriteBd(oBd, 0, 0)
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()
oFacOutEnc:FileClose()
// Decrypt the encrypted output file in a single call using CBC mode:
cDecryptedFile := "qa_output/hamlet_dec.xml"
nSuccess := oCrypt:CkDecryptFile(cOutputEncryptedFile, cDecryptedFile)
// Assume success for the example..
// Compare the contents of the decrypted file with the original file:
nBSame := oFacIn:FileContentsEqual(cFileToEncrypt, cDecryptedFile)
? "bSame = " + Str(nBSame)
oCrypt:destroy()
oFacIn:destroy()
oFacOutEnc:destroy()
oBd:destroy()