import 'dart:math'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; class LocalVaultService { LocalVaultService._(); static final LocalVaultService instance = LocalVaultService._(); static const String _encryptionKeyStorageKey = 'notes_local_encryption_key_v1'; final FlutterSecureStorage _secureStorage = FlutterSecureStorage(); String? _cachedEncryptionKey; Future readEncryptionKey() async { final String? cachedKey = _cachedEncryptionKey; if (cachedKey != null) { return cachedKey; } final String? storedKey = await _secureStorage.read( key: _encryptionKeyStorageKey, ); _cachedEncryptionKey = storedKey; return storedKey; } Future createEncryptionKey() async { final String encryptionKey = _generateEncryptionKey(); await _secureStorage.write( key: _encryptionKeyStorageKey, value: encryptionKey, ); _cachedEncryptionKey = encryptionKey; return encryptionKey; } Future clearEncryptionKey() async { await _secureStorage.delete(key: _encryptionKeyStorageKey); _cachedEncryptionKey = null; } String _generateEncryptionKey() { final Random random = Random.secure(); final List bytes = List.generate(32, (_) => random.nextInt(256)); return bytes .map((int byte) => byte.toRadixString(16).padLeft(2, '0')) .join(); } }