Flutter安全存储插件flutter_secure_storage_ohos的使用

Flutter安全存储插件flutter_secure_storage_ohos的使用

描述

flutter_secure_storage_ohos 是一个用于在安全存储中存储数据的 Flutter 插件。它使用 AES 加密来保护 Ohos 平台上的数据,AES 密钥通过 RSA 进行加密,RSA 密钥则存储在偏好设置中。

默认情况下,插件使用以下算法:

  • AES/CBC/PKCS7Padding 用于 AES 加密
  • RSA/ECB/PKCS1Padding 用于 RSA 加密

你也可以使用其他推荐的算法:

  • AES/GCM/NoPadding 用于 AES 加密
  • RSA/ECB/OAEPWithSHA-256AndMGF1Padding 用于 RSA 加密

可以通过在 OhosOptions 中设置这些算法:

OhosOptions _getOhosOptions() => const OhosOptions(
      ohosKeyCipherAlgorithm: OhosKeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding,
      ohosStorageCipherAlgorithm: OhosStorageCipherAlgorithm.AES_GCM_NoPadding,
  );

使用方法

添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_secure_storage_ohos: ^1.0.0

示例代码

示例代码完整实现

import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.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 }

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(),
      ohOptions: _getOhosOptions(),
    );

    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(),
      ohOptions: _getOhosOptions(),
    );
    _readAll();
  }

  Future<void> _addNewItem() async {
    final String key = _randomValue();
    final String value = _randomValue();

    await _storage.write(
      key: key,
      value: value,
      iOptions: _getIOSOptions(),
      aOptions: _getAndroidOptions(),
      ohOptions: _getOhosOptions(),
    );
    _readAll();
  }

  IOSOptions _getIOSOptions() => IOSOptions(
        accountName: _getAccountName(),
      );

  AndroidOptions _getAndroidOptions() => const AndroidOptions(
        encryptedSharedPreferences: true,
      );

  OhosOptions _getOhosOptions() => const OhosOptions(
    sharedPreferencesName: 'sharedPreferencesName',
  );

  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;
                }
              },
              itemBuilder: (BuildContext context) => <PopupMenuEntry<_Actions>>[
                const PopupMenuItem(
                  key: Key('delete_all'),
                  value: _Actions.deleteAll,
                  child: Text('Delete all'),
                ),
              ],
            )
          ],
        ),
        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(),
          ohOptions: _getOhosOptions(),
        );
        _readAll();

        break;
      case _ItemActions.edit:
        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(),
            ohOptions: _getOhosOptions(),
          );
          _readAll();
        }
        break;
      case _ItemActions.containsKey:
        final key = await _displayTextInputDialog(context, item.key);
        final result = await _storage.containsKey(key: key);
        if (!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(),
              ohOptions: _getOhosOptions());
        if (!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_ohos的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter安全存储插件flutter_secure_storage_ohos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_secure_storage_ohos 是一个用于在 OpenHarmony 平台上安全存储敏感数据的 Flutter 插件。它基于 flutter_secure_storage,并针对 OpenHarmony 进行了适配。使用该插件,你可以在 Flutter 应用中安全地存储和读取敏感信息,如 API 密钥、用户凭证等。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 flutter_secure_storage_ohos 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_secure_storage_ohos: ^1.0.0

然后运行 flutter pub get 来安装依赖。

使用插件

1. 导入插件

在需要使用 flutter_secure_storage_ohos 的 Dart 文件中导入插件:

import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart';

2. 创建 FlutterSecureStorage 实例

你可以通过以下方式创建一个 FlutterSecureStorage 实例:

final storage = FlutterSecureStorage();

3. 存储数据

使用 write 方法将数据安全地存储到设备中:

await storage.write(key: 'my_key', value: 'my_value');

4. 读取数据

使用 read 方法从设备中读取存储的数据:

String? value = await storage.read(key: 'my_key');
print(value); // 输出: my_value

5. 删除数据

使用 delete 方法删除存储的数据:

await storage.delete(key: 'my_key');

6. 删除所有数据

使用 deleteAll 方法删除所有存储的数据:

await storage.deleteAll();

7. 检查数据是否存在

使用 containsKey 方法检查某个键是否存在:

bool containsKey = await storage.containsKey(key: 'my_key');
print(containsKey); // 输出: true 或 false

示例代码

以下是一个完整的示例,展示了如何使用 flutter_secure_storage_ohos 进行数据的存储、读取和删除:

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final storage = FlutterSecureStorage();

  // 存储数据
  await storage.write(key: 'my_key', value: 'my_value');

  // 读取数据
  String? value = await storage.read(key: 'my_key');
  print('Stored value: $value');

  // 删除数据
  await storage.delete(key: 'my_key');

  // 检查数据是否存在
  bool containsKey = await storage.containsKey(key: 'my_key');
  print('Contains key: $containsKey');

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Secure Storage OHOS Example'),
        ),
        body: Center(
          child: Text('Check the console for output.'),
        ),
      ),
    );
  }
}
回到顶部