initEncrypter method

Future<Encrypter?> initEncrypter()

Initializes the encrypter used for encrypting files. This needs to be done on the main isolate as opposed to the worker since it requires access to plugins that are not easily available in the worker isolate context.

Implementation

Future<Encrypter?> initEncrypter() async {
  final persistorSettings = settings;

  // The encrypter is only initialized if the global settings are encrypted file persistor settings.
  if (persistorSettings is! FilePersistorSettings ||
      !persistorSettings.encryptionEnabled) {
    return null;
  }

  const storage = FlutterSecureStorage();
  final base64Key = await storage.read(key: secureStorageKey);
  Key key;

  if (base64Key != null) {
    key = Key.fromBase64(base64Key);
  } else {
    key = Key.fromSecureRandom(32);
    await storage.write(key: secureStorageKey, value: key.base64);
  }

  return Encrypter(AES(key, mode: AESMode.cbc));
}