encryptBytes method

  1. @override
Future<Uint8List> encryptBytes({
  1. required Uint8List plainBytes,
  2. required String key,
  3. String? iv,
})
override

Encrypts plainBytes and returns [16-byte IV][ciphertext].

When iv is provided it is used as the IV; otherwise a random IV is generated. The IV is always prepended to the returned bytes so that decryptBytes can reconstruct it without out-of-band information.

Implementation

@override
Future<Uint8List> encryptBytes({
  required Uint8List plainBytes,
  required String key,
  String? iv,
}) async {
  try {
    final keyBytes = prepareKey(key);
    final ivBytes = iv != null ? prepareIv(iv) : randomIv();
    final ciphertext = aesCtrCrypt(plainBytes, keyBytes, ivBytes);
    // Prepend the 16-byte IV — identical to the native file format.
    final output = Uint8List(16 + ciphertext.length);
    output.setRange(0, 16, ivBytes);
    output.setRange(16, output.length, ciphertext);
    return output;
  } catch (e, st) {
    dev.log('encryptBytes failed: $e', name: 'MethodChannelAesEncryptFile', error: e, stackTrace: st);
    rethrow;
  }
}