encrypt icon indicating copy to clipboard operation
encrypt copied to clipboard

Encryption Decryption in chunks

Open aliaafreen opened this issue 3 years ago • 3 comments

How can we encrypt and decrypt a large file of 500mb into chunks?

aliaafreen avatar Jun 17 '21 11:06 aliaafreen

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 avatar Oct 23 '21 00:10 Abdelazeem777

@Abdelazeem777 Would the reverse work for decrypting?

adil192 avatar Jun 28 '23 17:06 adil192

@adil192 Yes, but the chunk size must be the same like the encryption process.

Abdelazeem777 avatar Jun 28 '23 20:06 Abdelazeem777