import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive_flutter/adapters.dart'; import 'package:paperless_mobile/core/config/hive/hive_config.dart'; import 'package:paperless_mobile/core/database/tables/global_settings.dart'; import 'package:paperless_mobile/core/database/tables/local_user_account.dart'; import 'package:paperless_mobile/core/database/tables/local_user_app_state.dart'; import 'package:paperless_mobile/core/database/tables/local_user_settings.dart'; /// /// Opens an encrypted box, calls [callback] with the now opened box, awaits /// [callback] to return and returns the calculated value. Closes the box after. /// Future withEncryptedBox( String name, FutureOr Function(Box box) callback, ) async { final key = await _getEncryptedBoxKey(); final box = await Hive.openBox( name, encryptionCipher: HiveAesCipher(key), ); final result = await callback(box); await box.close(); return result; } Future _getEncryptedBoxKey() async { const secureStorage = FlutterSecureStorage( aOptions: AndroidOptions( encryptedSharedPreferences: true, ), ); if (!await secureStorage.containsKey(key: 'key')) { final key = Hive.generateSecureKey(); await secureStorage.write( key: 'key', value: base64UrlEncode(key), ); } final key = (await secureStorage.read(key: 'key'))!; return base64Decode(key); } extension HiveBoxAccessors on HiveInterface { Box get settingsBox => box(HiveBoxes.globalSettings); Box get localUserAccountBox => box(HiveBoxes.localUserAccount); Box get localUserAppStateBox => box(HiveBoxes.localUserAppState); Box get localUserSettingsBox => box(HiveBoxes.localUserSettings); Box get globalSettingsBox => box(HiveBoxes.globalSettings); }