Flutter安全存储插件flutter_secure_storage_per的使用
Flutter 安全存储插件 flutter_secure_storage 的使用
注意事项
当在 Android 上使用 encryptedSharedPreferences
参数时,确保将其传递给构造函数而不是函数。例如:
AndroidOptions _getAndroidOptions() => const AndroidOptions(
encryptedSharedPreferences: true,
);
final storage = FlutterSecureStorage(aOptions: _getAndroidOptions());
这将防止由于混合使用 encryptedSharedPreferences
而导致的错误。有关详细信息,请参阅 此问题。
介绍
这是一个用于在安全存储中存储数据的 Flutter 插件:
- iOS 使用的是 Keychain。
- Android 使用 AES 加密,AES 密钥通过 RSA 加密,并且 RSA 密钥存储在 KeyStore 中。
- 从 V5.0.0 开始,我们可以通过启用 Android 选项来在 Android 上使用 EncryptedSharedPreferences:
AndroidOptions _getAndroidOptions() => const AndroidOptions(
encryptedSharedPreferences: true,
);
对于更多详细信息,请查看示例应用程序。
- 在 Linux 上使用的是 libsecret。
- 注意:KeyStore 是在 Android 4.3(API 级别 18)中引入的。该插件不适用于更早版本。
开始使用
以下是如何使用 flutter_secure_storage
插件的基本示例:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// 创建存储对象
final storage = FlutterSecureStorage();
// 读取值
String value = await storage.read(key: key);
// 读取所有值
Map<String, String> allValues = await storage.readAll();
// 删除值
await storage.delete(key: key);
// 删除所有值
await storage.deleteAll();
// 写入值
await storage.write(key: key, value: value);
要使应用能够在后台获取安全值,可以指定 first_unlock
或 first_unlock_this_device
。默认情况下,如果没有指定,则为解锁状态。例如:
final options = IOSOptions(accessibility: KeychainAccessibility.first_unlock);
await storage.write(key: key, value: value, iOptions: options);
配置 Android 版本
在 [项目]/android/app/build.gradle
文件中设置 minSdkVersion
大于等于 18:
android {
...
defaultConfig {
...
minSdkVersion 18
...
}
}
注意:默认情况下,Android 会在 Google Drive 上备份数据,这可能会导致 java.security.InvalidKeyException: Failed to unwrap key
异常。你需要:
配置 Web 版本
Flutter Secure Storage 使用实验性的 WebCrypto 实现。目前使用它存在风险。反馈欢迎以改善它。浏览器会创建私钥,因此本地存储中的加密字符串不能移植到其他浏览器或机器上,并且只能在同一域下工作。
非常重要:如果你没有启用 HTTP Strict Forward Secrecy 并正确设置响应头,你可能会受到 JavaScript 劫持的影响。请参阅:
配置 Linux 版本
在你的机器上需要安装 libsecret-1-dev
和 libjsoncpp-dev
来构建项目,还需要安装 libsecret-1-0
和 libjsoncpp1
来运行应用(打包后作为依赖项添加)。如果使用 snapcraft
构建项目,请使用以下配置:
parts:
uet-lms:
source: .
plugin: flutter
flutter-target: lib/main.dart
build-packages:
- libsecret-1-dev
- libjsoncpp-dev
stage-packages:
- libsecret-1-0
- libjsoncpp-dev
配置 Windows 版本
注意:当前实现不支持 readAll
和 deleteAll
,并且可能会发生变化。
配置 macOS 版本
你也需要在 macOS 运行器中添加 Keychain 共享功能。为此,请在 macos/Runner/DebugProfile.entitlements
和 macos/Runner/Release.entitlements
文件中添加以下内容(两个文件都需要更改):
<key>keychain-access-groups</key>
<array/>
集成测试
从 example
目录运行以下命令:
flutter drive --target=test_driver/app.dart
完整示例 Demo
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
void main() {
runApp(const MaterialApp(home: ItemsWidget()));
}
class ItemsWidget extends StatefulWidget {
const ItemsWidget({Key? key}) : super(key: key);
[@override](/user/override)
ItemsWidgetState createState() => ItemsWidgetState();
}
enum _Actions { deleteAll, isProtectedDataAvailable }
enum _ItemActions { delete, edit, containsKey, read }
class ItemsWidgetState extends State<ItemsWidget> {
final _storage = const FlutterSecureStorage();
final _accountNameController = TextEditingController(text: 'flutter_secure_storage_service');
List<_SecItem> _items = [];
[@override](/user/override)
void initState() {
super.initState();
_accountNameController.addListener(() => _readAll());
_readAll();
}
Future<void> _readAll() async {
final all = await _storage.readAll(
iOptions: _getIOSOptions(),
aOptions: _getAndroidOptions(),
);
setState(() {
_items = all.entries
.map((entry) => _SecItem(entry.key, entry.value))
.toList(growable: false);
});
}
Future<void> _deleteAll() async {
await _storage.deleteAll(
iOptions: _getIOSOptions(),
aOptions: _getAndroidOptions(),
);
_readAll();
}
Future<void> _isProtectedDataAvailable() async {
final scaffold = ScaffoldMessenger.of(context);
final result = await _storage.isCupertinoProtectedDataAvailable();
scaffold.showSnackBar(
SnackBar(
content: Text('Protected data available: $result'),
backgroundColor: result != null && result ? Colors.green : Colors.red,
),
);
}
Future<void> _addNewItem() async {
final String key = _randomValue();
final String value = _randomValue();
await _storage.write(
key: key,
value: value,
iOptions: _getIOSOptions(),
aOptions: _getAndroidOptions(),
);
_readAll();
}
IOSOptions _getIOSOptions() => IOSOptions(
accountName: _getAccountName(),
);
AndroidOptions _getAndroidOptions() => const AndroidOptions(
encryptedSharedPreferences: true,
);
String? _getAccountName() =>
_accountNameController.text.isEmpty ? null : _accountNameController.text;
[@override](/user/override)
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
actions: <Widget>[
IconButton(
key: const Key('add_random'),
onPressed: _addNewItem,
icon: const Icon(Icons.add),
),
PopupMenuButton<_Actions>(
key: const Key('popup_menu'),
onSelected: (action) {
switch (action) {
case _Actions.deleteAll:
_deleteAll();
break;
case _Actions.isProtectedDataAvailable:
_isProtectedDataAvailable();
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<_Actions>>[
const PopupMenuItem(
key: Key('delete_all'),
value: _Actions.deleteAll,
child: Text('Delete all'),
),
const PopupMenuItem(
key: Key('is_protected_data_available'),
value: _Actions.isProtectedDataAvailable,
child: Text('IsProtectedDataAvailable'),
),
],
),
],
),
body: Column(
children: [
if (!kIsWeb && Platform.isIOS)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextFormField(
controller: _accountNameController,
decoration: const InputDecoration(labelText: 'kSecAttrService'),
),
),
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (BuildContext context, int index) => ListTile(
trailing: PopupMenuButton(
key: Key('popup_row_$index'),
onSelected: (_ItemActions action) => _performAction(action, _items[index], context),
itemBuilder: (BuildContext context) => <PopupMenuEntry<_ItemActions>>[
PopupMenuItem(
value: _ItemActions.delete,
child: Text('Delete', key: Key('delete_row_$index')),
),
PopupMenuItem(
value: _ItemActions.edit,
child: Text('Edit', key: Key('edit_row_$index')),
),
PopupMenuItem(
value: _ItemActions.containsKey,
child: Text('Contains Key', key: Key('contains_row_$index')),
),
PopupMenuItem(
value: _ItemActions.read,
child: Text('Read', key: Key('contains_row_$index')),
),
],
),
title: Text(
_items[index].value,
key: Key('title_row_$index'),
),
subtitle: Text(
_items[index].key,
key: Key('subtitle_row_$index'),
),
),
),
),
],
),
);
Future<void> _performAction(
_ItemActions action,
_SecItem item,
BuildContext context,
) async {
switch (action) {
case _ItemActions.delete:
await _storage.delete(
key: item.key,
iOptions: _getIOSOptions(),
aOptions: _getAndroidOptions(),
);
_readAll();
break;
case _ItemActions.edit:
if (!context.mounted) return;
final result = await showDialog<String>(
context: context,
builder: (context) => _EditItemWidget(item.value),
);
if (result != null) {
await _storage.write(
key: item.key,
value: result,
iOptions: _getIOSOptions(),
aOptions: _getAndroidOptions(),
);
_readAll();
}
break;
case _ItemActions.containsKey:
final key = await _displayTextInputDialog(context, item.key);
final result = await _storage.containsKey(key: key);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Contains Key: $result, key checked: $key'),
backgroundColor: result ? Colors.green : Colors.red,
),
);
break;
case _ItemActions.read:
final key = await _displayTextInputDialog(context, item.key);
final result = await _storage.read(key: key, aOptions: _getAndroidOptions());
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('value: $result'),
),
);
break;
}
}
Future<String> _displayTextInputDialog(
BuildContext context,
String key,
) async {
final controller = TextEditingController();
controller.text = key;
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Check if key exists'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('OK'),
),
],
content: TextField(
controller: controller,
),
);
},
);
return controller.text;
}
String _randomValue() {
final rand = Random();
final codeUnits = List.generate(20, (index) {
return rand.nextInt(26) + 65;
});
return String.fromCharCodes(codeUnits);
}
}
class _EditItemWidget extends StatelessWidget {
_EditItemWidget(String text)
: _controller = TextEditingController(text: text);
final TextEditingController _controller;
[@override](/user/override)
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Edit item'),
content: TextField(
key: const Key('title_field'),
controller: _controller,
autofocus: true,
),
actions: <Widget>[
TextButton(
key: const Key('cancel'),
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
TextButton(
key: const Key('save'),
onPressed: () => Navigator.of(context).pop(_controller.text),
child: const Text('Save'),
),
],
);
}
}
class _SecItem {
_SecItem(this.key, this.value);
final String key;
final String value;
}
更多关于Flutter安全存储插件flutter_secure_storage_per的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter安全存储插件flutter_secure_storage_per的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,flutter_secure_storage_per
是一个用于在 Flutter 应用中安全存储敏感数据的插件。它提供了对平台安全存储的访问,例如在 Android 上的 Keystore 和在 iOS 上的 Keychain。
以下是一个使用 flutter_secure_storage_per
插件的示例代码,展示了如何存储和读取数据。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 flutter_secure_storage_per
依赖:
dependencies:
flutter:
sdk: flutter
flutter_secure_storage_per: ^x.y.z # 请替换为最新版本号
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入插件:
import 'package:flutter_secure_storage_per/flutter_secure_storage_per.dart';
3. 初始化存储
通常,你会在应用启动时初始化存储:
final FlutterSecureStorage storage = FlutterSecureStorage();
4. 存储数据
使用 write
方法存储数据:
Future<void> storeData() async {
final String key = 'my_secure_key';
final String value = 'my_secure_value';
await storage.write(key: key, value: value);
print('Data stored successfully.');
}
5. 读取数据
使用 read
方法读取数据:
Future<void> readData() async {
final String key = 'my_secure_key';
String? value = await storage.read(key: key);
if (value != null) {
print('Data read successfully: $value');
} else {
print('No data found for key: $key');
}
}
6. 删除数据
使用 delete
方法删除数据:
Future<void> deleteData() async {
final String key = 'my_secure_key';
await storage.delete(key: key);
print('Data deleted successfully.');
}
7. 清空所有存储的数据
使用 deleteAll
方法清空所有存储的数据:
Future<void> clearAllData() async {
await storage.deleteAll();
print('All data cleared successfully.');
}
完整示例
以下是一个完整的示例,将所有步骤整合在一起:
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage_per/flutter_secure_storage_per.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final FlutterSecureStorage storage = FlutterSecureStorage();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Secure Storage Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
await storeData(storage);
},
child: Text('Store Data'),
),
ElevatedButton(
onPressed: () async {
await readData(storage);
},
child: Text('Read Data'),
),
ElevatedButton(
onPressed: () async {
await deleteData(storage);
},
child: Text('Delete Data'),
),
ElevatedButton(
onPressed: () async {
await clearAllData(storage);
},
child: Text('Clear All Data'),
),
],
),
),
),
);
}
Future<void> storeData(FlutterSecureStorage storage) async {
final String key = 'my_secure_key';
final String value = 'my_secure_value';
await storage.write(key: key, value: value);
print('Data stored successfully.');
}
Future<void> readData(FlutterSecureStorage storage) async {
final String key = 'my_secure_key';
String? value = await storage.read(key: key);
if (value != null) {
print('Data read successfully: $value');
// You can use ScaffoldMessenger to show a Snackbar or update the UI here
} else {
print('No data found for key: $key');
}
}
Future<void> deleteData(FlutterSecureStorage storage) async {
final String key = 'my_secure_key';
await storage.delete(key: key);
print('Data deleted successfully.');
}
Future<void> clearAllData(FlutterSecureStorage storage) async {
await storage.deleteAll();
print('All data cleared successfully.');
}
}
这个示例应用展示了如何使用 flutter_secure_storage_per
插件来存储、读取、删除和清空安全存储中的数据。你可以根据需要进一步定制和扩展这些功能。