aesCtrEncryptRange static method

Future<Uint8List> aesCtrEncryptRange({
  1. required String path,
  2. required int pos,
  3. required int size,
  4. required Uint8List key,
  5. required Uint8List iv,
})

Encrypts file[pos .. pos+size) and returns the ciphertext. The native side opens path, seeks to pos, reads size bytes, and encrypts them off the platform main thread — only the ciphertext crosses the channel, so a large attachment never copies its plaintext into the Dart heap.

key must be 32 bytes (AES-256), iv 16 (the initial counter block). pos may be non-16-aligned (the backend partitions parts on arbitrary offsets); the counter is advanced by pos >> 4 blocks and pos & 15 keystream bytes discarded so the slice stays aligned with a continuous stream from offset 0.

Never returns null: when native hardware AES is unavailable or fails, it falls back to reading the range and encrypting on a background isolate (range_fallback.encryptRangeFallback → encryptChunk). The fallback guards a short read (a truncated source fails loud, like the native side).

Implementation

static Future<Uint8List> aesCtrEncryptRange({
  required String path,
  required int pos,
  required int size,
  required Uint8List key,
  required Uint8List iv,
}) async {
  assert(key.length == 32, 'AES-256 key must be 32 bytes, got ${key.length}');
  assert(iv.length == 16, 'CTR IV must be 16 bytes, got ${iv.length}');
  assert(pos >= 0 && size >= 0, 'pos/size must be non-negative');
  if (isSupported) {
    try {
      final native = await _channel.invokeMethod<Uint8List>(
        'aesCtrRange',
        <String, Object?>{
          'path': path,
          'pos': pos,
          'size': size,
          'key': key,
          'iv': iv,
        },
      );
      if (native != null) return native;
    } catch (e) {
      // A native error (PlatformException) or a host with no registered
      // plugin (MissingPluginException under flutter test) — both fall back
      // to the Dart path. Log it: a fallback on a device that SHOULD have
      // hardware AES is the anomaly worth seeing.
      debugPrint(
        'ux/crypto: native aesCtrRange unavailable ($e); Dart fallback',
      );
    }
  }
  return range_fallback.encryptRangeFallback(path, pos, size, key, iv);
}