encrypt
encrypt copied to clipboard
Encryption Decryption in chunks
How can we encrypt and decrypt a large file of 500mb into chunks?
Here you can read File
as chunks of bytes, every chunk is 5MB size.
Stream<Uint8List> _getStreamOfBytes(File inFile) async* {
final fileLength = await inFile.length();
final accessFile = await inFile.open();
const chunkSize = 5242880; // 5MB
for (var startPosition = 0;
startPosition < fileLength;
startPosition += chunkSize) {
await accessFile.setPosition(startPosition);
final chunk = await accessFile.read(chunkSize);
yield chunk;
}
}
And then you can encrypt or decrypt every single chunk on its own like the following
main(){
final inputFile = File('test/assets/test.txt');
final key = Key.fromUtf8(_generateKey(_key));
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(key, mode: AESMode.ctr, padding: null));
final outputFile = File('test/assets/test_encrypted.txt');
await for (var chunkBytes in _getStreamOfBytes(inputFile)) {
final encrypted = encrypter.encryptBytes(chunkBytes, iv: iv);
final encryptedBytes = encrypted.bytes;
outputFile.writeAsBytesSync(encryptedBytes, mode: FileMode.append);
}
}
@Abdelazeem777 Would the reverse work for decrypting?
@adil192 Yes, but the chunk size must be the same like the encryption process.