Files
notas/lib/data/local_vault_service.dart
T

56 lines
1.4 KiB
Dart

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<String?> readEncryptionKey() async {
final String? cachedKey = _cachedEncryptionKey;
if (cachedKey != null) {
return cachedKey;
}
final String? storedKey = await _secureStorage.read(
key: _encryptionKeyStorageKey,
);
_cachedEncryptionKey = storedKey;
return storedKey;
}
Future<String> createEncryptionKey() async {
final String encryptionKey = _generateEncryptionKey();
await _secureStorage.write(
key: _encryptionKeyStorageKey,
value: encryptionKey,
);
_cachedEncryptionKey = encryptionKey;
return encryptionKey;
}
Future<void> clearEncryptionKey() async {
await _secureStorage.delete(key: _encryptionKeyStorageKey);
_cachedEncryptionKey = null;
}
String _generateEncryptionKey() {
final Random random = Random.secure();
final List<int> bytes = List<int>.generate(32, (_) => random.nextInt(256));
return bytes
.map((int byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
}
}