processBytes method
Returns a new Uint8List with the transformed inputBytes.
Encryption and decryption are identical for ChaCha20.
The initial state is preserved, so the method can be called repeatedly.
Implementation
Uint8List processBytes(Uint8List inputBytes) {
final initial = Uint32List.fromList(chaChaState);
final out = Uint8List(inputBytes.length);
final keyStream = Uint8List(64);
final bd = ByteData.sublistView(keyStream);
for (int offset = 0, block = 0;
offset < inputBytes.length;
offset += 64, block++) {
// Each block starts from the initial state with counter + j
chaChaState = Uint32List.fromList(initial);
chaChaState[12] = (initial[12] + block) & 0xFFFFFFFF;
chaCha20();
// Serialize explicitly as little-endian (RFC 7539, section 2.3)
for (int i = 0; i < 16; i++) {
bd.setUint32(i * 4, chaChaState[i], Endian.little);
}
// The last block may be shorter than 64 bytes
final n = min(64, inputBytes.length - offset);
for (int i = 0; i < n; i++) {
out[offset + i] = inputBytes[offset + i] ^ keyStream[i];
}
}
chaChaState = initial; // Restore the initial state
return out;
}