init method
Initializes the secure storage repository.
This method should be called as early as possible in the application lifecycle. It ensures that a secure encryption key is generated and stored securely.
- If an encryption key does not exist, it generates a new one.
- If an error occurs while reading the encryption key, it clears secure storage.
Returns an instance of StorageRepository once initialization is complete.
Implementation
@override
Future<StorageRepository> init() async {
const encryptionKeyStorageKey = StorageRepositoryKeys.encryptionKey;
var containsEncryptionKey = false;
try {
// Check if an encryption key already exists in secure storage.
containsEncryptionKey =
await flutterSecureStorage.read(key: encryptionKeyStorageKey) != null;
} on PlatformException catch (_) {
// If there's an error accessing secure storage, clear all stored data.
await flutterSecureStorage.deleteAll();
}
// If no encryption key exists, generate a new one and store it securely.
if (!containsEncryptionKey) {
final secureEncryptionKey = base64UrlEncode(Hive.generateSecureKey());
await flutterSecureStorage.write(
key: encryptionKeyStorageKey,
value: secureEncryptionKey,
);
}
// Retrieve and decode the encryption key for Hive storage.
final encryptionKeyValue = base64Url.decode(
await flutterSecureStorage.read(key: encryptionKeyStorageKey) ?? '',
);
// Open a Hive box with AES encryption.
storage = await Hive.openBox(
key,
encryptionCipher: HiveAesCipher(encryptionKeyValue),
);
return this;
}