rotateEncryptionKey method

Future<void> rotateEncryptionKey()

Rotate the encryption key (advanced feature)

Implementation

Future<void> rotateEncryptionKey() async {
  _checkInit();
  try {
    await _withLock(() async {
      // Read all current data (decrypted)
      final allKeys = await getAllKeys();
      final allData = <String, String>{};

      for (var key in allKeys) {
        final value = await getString(key);
        if (value != null) {
          allData[key] = value;
        }
      }

      // Generate new key
      _key = encrypt.Key.fromSecureRandom(32);
      final newKeyStr = base64Url.encode(_key.bytes);
      await _secureStorage.write(key: _keyIdentifier, value: newKeyStr);

      // Clear cache before re-encryption
      _cache.clear();
      _cacheAccessOrder.clear();

      // Re-encrypt all data with new key
      await Future.wait(
        allData.entries.map((entry) => setString(entry.key, entry.value)),
      );
    });
  } catch (e) {
    throw SecureStorageException('Failed to rotate encryption key', e);
  }
}