fluttertpc_flutter_secure_storage 在鸿蒙上的使用指南

1. 插件介绍

fluttertpc_flutter_secure_storage 是一个基于 flutter_secure_storage 开发的 Flutter 插件,专为鸿蒙(HarmonyOS)平台进行了适配。该插件提供了安全存储敏感数据的能力,支持使用加密算法保护存储的数据,确保用户隐私和数据安全。

主要特性:

  • 支持多种加密算法(RSA、AES)
  • 提供灵活的配置选项
  • 与原生鸿蒙系统的安全存储机制集成
  • 支持自定义 SharedPreferences 名称和密钥前缀
  • 跨平台兼容设计,可在多端使用相同的 API

2. 插件安装

由于这是自定义修改版本,需要以 Git 形式引入依赖。在项目的 pubspec.yaml 文件中添加以下配置:

dependencies:
  flutter_secure_storage_ohos:
    git:
      url: "https://gitcode.com/openharmony-sig/fluttertpc_flutter_secure_storage.git"
      path: "flutter_secure_storage_ohos"

添加依赖后,执行以下命令获取插件:

flutter pub get

3. API 使用指南

3.1 初始化插件

import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart';

// 创建实例
final storage = const FlutterSecureStorage();

3.2 配置选项(OhosOptions)

鸿蒙平台支持以下配置选项:

参数名称描述默认值
encryptedSharedPreferences是否使用加密的 SharedPreferencesfalse
resetOnError发生错误时是否自动重置所有数据false
ohosKeyCipherAlgorithm加密密钥的算法RSA_ECB_PKCS1Padding
ohosStorageCipherAlgorithm加密存储内容的算法AES_CBC_PKCS7Padding
sharedPreferencesName自定义 SharedPreferences 数据库名称默认
preferencesKeyPrefix密钥前缀,确保唯一性默认

支持的加密算法:

  • 密钥加密算法:RSA_ECB_PKCS1Padding、RSA_ECB_OAEPwithSHA_256andMGF1Padding
  • 存储加密算法:AES_CBC_PKCS7Padding

3.3 基本操作

3.3.1 写入数据
await storage.write(
  key: 'user_token',
  value: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
    ohosKeyCipherAlgorithm: OhosKeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding,
    encryptedSharedPreferences: true,
  ),
);
3.3.2 读取数据
String? token = await storage.read(
  key: 'user_token',
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
  ),
);
3.3.3 检查密钥是否存在
bool exists = await storage.containsKey(
  key: 'user_token',
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
  ),
);
3.3.4 删除数据
await storage.delete(
  key: 'user_token',
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
  ),
);
3.3.5 读取所有数据
Map<String, String> allData = await storage.readAll(
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
  ),
);
3.3.6 删除所有数据
await storage.deleteAll(
  ohOptions: OhosOptions(
    sharedPreferencesName: 'my_app_preferences',
  ),
);

4. 完整示例代码

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

void main() {
  runApp(const MaterialApp(home: SecureStorageExample()));
}

class SecureStorageExample extends StatefulWidget {
  const SecureStorageExample({Key? key}) : super(key: key);

  
  SecureStorageExampleState createState() => SecureStorageExampleState();
}

class SecureStorageExampleState extends State<SecureStorageExample> {
  final _storage = const FlutterSecureStorage();
  final _keyController = TextEditingController();
  final _valueController = TextEditingController();
  String _result = '';

  // 获取鸿蒙平台配置
  OhosOptions _getOhosOptions() => const OhosOptions(
        sharedPreferencesName: 'my_app_preferences',
        ohosKeyCipherAlgorithm: OhosKeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding,
        encryptedSharedPreferences: true,
      );

  // 写入数据
  Future<void> _writeData() async {
    if (_keyController.text.isEmpty || _valueController.text.isEmpty) {
      setState(() => _result = '请输入密钥和值');
      return;
    }

    await _storage.write(
      key: _keyController.text,
      value: _valueController.text,
      ohOptions: _getOhosOptions(),
    );
    setState(() => _result = '数据写入成功');
  }

  // 读取数据
  Future<void> _readData() async {
    if (_keyController.text.isEmpty) {
      setState(() => _result = '请输入密钥');
      return;
    }

    String? value = await _storage.read(
      key: _keyController.text,
      ohOptions: _getOhosOptions(),
    );
    setState(() => _result = '读取结果: ${value ?? '未找到数据'}');
  }

  // 读取所有数据
  Future<void> _readAllData() async {
    Map<String, String> allData = await _storage.readAll(
      ohOptions: _getOhosOptions(),
    );
    setState(() {
      _result = '所有数据:\n${allData.entries.map((e) => '${e.key}: ${e.value}').join('\n')}';
    });
  }

  // 删除数据
  Future<void> _deleteData() async {
    if (_keyController.text.isEmpty) {
      setState(() => _result = '请输入密钥');
      return;
    }

    await _storage.delete(
      key: _keyController.text,
      ohOptions: _getOhosOptions(),
    );
    setState(() => _result = '数据删除成功');
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Secure Storage 示例')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _keyController,
              decoration: const InputDecoration(labelText: '密钥'),
            ),
            TextField(
              controller: _valueController,
              decoration: const InputDecoration(labelText: '值'),
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(onPressed: _writeData, child: const Text('写入')),
                ElevatedButton(onPressed: _readData, child: const Text('读取')),
                ElevatedButton(onPressed: _deleteData, child: const Text('删除')),
              ],
            ),
            const SizedBox(height: 10),
            ElevatedButton(onPressed: _readAllData, child: const Text('读取所有')),
            const SizedBox(height: 20),
            Text(_result, style: const TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}

4. 总结

fluttertpc_flutter_secure_storage 为 Flutter 开发者提供了在鸿蒙平台上安全存储敏感数据的解决方案。通过使用该插件,开发者可以:

  1. 安全地存储用户凭证、令牌、加密密钥等敏感信息
  2. 利用鸿蒙系统的原生安全机制保护数据
  3. 灵活配置加密算法和存储选项
  4. 使用与其他平台一致的 API,简化跨端开发

该插件的适配工作使得 Flutter 开发者能够在鸿蒙平台上轻松实现数据安全存储功能,为用户提供更安全的应用体验。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.youkuaiyun.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值