Dart
Dart
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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
final crypt = CkCrypt2();
crypt.cryptAlgorithm = 'aes';
crypt.cipherMode = 'cbc';
crypt.keyLength = 256;
crypt.setEncodedKey('000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F', 'hex');
crypt.setEncodedIV('000102030405060708090A0B0C0D0E0F', 'hex');
final fileToEncrypt = 'qa_data/hamlet.xml';
final facIn = CkFileAccess();
try {
facIn.openForRead(fileToEncrypt);
} on ChilkatException {
print('Failed to open file that is to be encrytped.');
return;
}
final outputEncryptedFile = 'c:/temp/qa_output/hamlet.enc';
final facOutEnc = CkFileAccess();
try {
facOutEnc.openForWrite(outputEncryptedFile);
} on ChilkatException {
print('Failed to encrypted output file.');
return;
}
// Let's encrypt in 10000 byte chunks.
final chunkSize = 10000;
final numChunks = facIn.getNumBlocks(chunkSize);
crypt.firstChunk = true;
crypt.lastChunk = false;
final bd = CkBinData();
var i = 0;
while (i < numChunks) {
i++;
if (i == numChunks) {
crypt.lastChunk = true;
}
// Read the next chunk from the file.
// The last chunk will be whatever amount remains in the file..
bd.clear();
facIn.fileReadBd(chunkSize, bd);
// Encrypt.
crypt.encryptBd(bd);
// Write the encrypted chunk to the output file.
facOutEnc.fileWriteBd(bd, 0, 0);
crypt.firstChunk = false;
}
// Make sure both FirstChunk and LastChunk are restored to true after
// encrypting or decrypting in chunks. Otherwise subsequent encryptions/decryptions
// will produce unexpected results.
crypt.firstChunk = true;
crypt.lastChunk = true;
facIn.fileClose();
facOutEnc.fileClose();
// Decrypt the encrypted output file in a single call using CBC mode:
final decryptedFile = 'qa_output/hamlet_dec.xml';
crypt.ckDecryptFile(outputEncryptedFile, decryptedFile);
// Assume success for the example..
// Compare the contents of the decrypted file with the original file:
final bSame = facIn.fileContentsEqual(fileToEncrypt, decryptedFile);
print('bSame = $bSame');
}