encryptChunk function
Encrypts plain under AES-256-CTR with key and base counter block
baseIv, producing the keystream bytes that a streaming cipher initialised
at offset 0 would produce at byte positions [pos, pos + plain.length).
Counter is advanced by pos / 16 blocks so the cipher is on the right AES
block. If pos % 16 != 0, the first pos % 16 keystream bytes of that block
are discarded so the cipher's internal within-block state aligns with byte
position pos. Returns a fresh Uint8List; baseIv is not mutated.
Implementation
Uint8List encryptChunk(
Uint8List key,
Uint8List baseIv,
int pos,
Uint8List plain,
) {
final chunkIv = Uint8List.fromList(baseIv);
incCounter(chunkIv, pos >> 4);
final cipher = SICStreamCipher(AESEngine())
..init(true, ParametersWithIV<KeyParameter>(KeyParameter(key), chunkIv));
final byteOffset = pos & 15;
if (byteOffset != 0) {
// Consume `byteOffset` keystream bytes so the cipher is positioned at byte
// `byteOffset` of block `pos / 16`, matching where a continuous streaming
// cipher would be after processing `pos` bytes.
final discardIn = Uint8List(byteOffset);
final discardOut = Uint8List(byteOffset);
cipher.processBytes(discardIn, 0, byteOffset, discardOut, 0);
}
final out = Uint8List(plain.length);
cipher.processBytes(plain, 0, plain.length, out, 0);
return out;
}