Visual FoxPro
Visual FoxPro
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 Visual FoxPro Downloads
LOCAL lnSuccess
LOCAL loCrypt
LOCAL lcFileToEncrypt
LOCAL loFacIn
LOCAL lcOutputEncryptedFile
LOCAL loFacOutEnc
LOCAL lnChunkSize
LOCAL lnNumChunks
LOCAL loBd
LOCAL i
LOCAL lcDecryptedFile
LOCAL lnBSame
lnSuccess = 0
* This example assumes the Chilkat API to have been previously unlocked.
* See Global Unlock Sample for sample code.
loCrypt = CreateObject('Chilkat.Crypt2')
loCrypt.CryptAlgorithm = "aes"
loCrypt.CipherMode = "cbc"
loCrypt.KeyLength = 256
loCrypt.SetEncodedKey("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F","hex")
loCrypt.SetEncodedIV("000102030405060708090A0B0C0D0E0F","hex")
lcFileToEncrypt = "qa_data/hamlet.xml"
loFacIn = CreateObject('Chilkat.FileAccess')
lnSuccess = loFacIn.OpenForRead(lcFileToEncrypt)
IF (lnSuccess <> 1) THEN
? "Failed to open file that is to be encrytped."
RELEASE loCrypt
RELEASE loFacIn
CANCEL
ENDIF
lcOutputEncryptedFile = "c:/temp/qa_output/hamlet.enc"
loFacOutEnc = CreateObject('Chilkat.FileAccess')
lnSuccess = loFacOutEnc.OpenForWrite(lcOutputEncryptedFile)
IF (lnSuccess <> 1) THEN
? "Failed to encrypted output file."
RELEASE loCrypt
RELEASE loFacIn
RELEASE loFacOutEnc
CANCEL
ENDIF
* Let's encrypt in 10000 byte chunks.
lnChunkSize = 10000
lnNumChunks = loFacIn.GetNumBlocks(lnChunkSize)
loCrypt.FirstChunk = 1
loCrypt.LastChunk = 0
loBd = CreateObject('Chilkat.BinData')
i = 0
DO WHILE i < lnNumChunks
i = i + 1
IF (i = lnNumChunks) THEN
loCrypt.LastChunk = 1
ENDIF
* Read the next chunk from the file.
* The last chunk will be whatever amount remains in the file..
loBd.Clear()
loFacIn.FileReadBd(lnChunkSize,loBd)
* Encrypt.
loCrypt.EncryptBd(loBd)
* Write the encrypted chunk to the output file.
loFacOutEnc.FileWriteBd(loBd,0,0)
loCrypt.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.
loCrypt.FirstChunk = 1
loCrypt.LastChunk = 1
loFacIn.FileClose()
loFacOutEnc.FileClose()
* Decrypt the encrypted output file in a single call using CBC mode:
lcDecryptedFile = "qa_output/hamlet_dec.xml"
lnSuccess = loCrypt.CkDecryptFile(lcOutputEncryptedFile,lcDecryptedFile)
* Assume success for the example..
* Compare the contents of the decrypted file with the original file:
lnBSame = loFacIn.FileContentsEqual(lcFileToEncrypt,lcDecryptedFile)
? "bSame = " + STR(lnBSame)
RELEASE loCrypt
RELEASE loFacIn
RELEASE loFacOutEnc
RELEASE loBd