Flutter数据库加密插件encrypt_db的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter数据库加密插件encrypt_db的使用

描述

encrypt_db 是一个用于使用AES-256加密算法加密和解密数据的Flutter插件。您可以使用此插件将敏感数据存储在本地存储中。 例如:用户凭据、API密钥、Bearer令牌等。

为什么使用这个插件?

  • 此插件使用AES-256加密算法来加密和解密数据。
  • 此插件使用Keychain(iOS)和KeyStore(Android)来存储加密密钥。
  • 此插件可以存储Stringintdoublebool 数据类型。

安装

在您的应用的 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  encrypt_db: latest_version

入门指南

读取和写入

_encrytDbPlugin.write(key: 'key1', value: 'value1'); /// 返回无值,但写入一个值
_encrytDbPlugin.read(key: 'key1', defaultValue: ''); /// 返回与defaultValue类型相同的值
_encrytDbPlugin.readAll(); /// 返回一个 Map<String, dynamic> 

清除所有数据和清除特定键

_encrytDbPlugin.clearAll(); /// 返回无值,但清除所有数据
_encrytDbPlugin.clear(key: 'key1'); /// 返回无值,但清除一个特定键

示例

import 'package:encrypt_db/encrypt_db.dart';

main() async {
  var _encryptDbPlugin = new EncryptDb();
  
  var result = await _encryptDbPlugin.readAll();
  debugPrint('result0: $result');
  
  await _encryptDbPlugin.clearAll();
  debugPrint('Clear all');
  
  result = await _encryptDbPlugin.readAll();
  debugPrint('result1: $result');
  
  _encryptDbPlugin.write(key: 'key1', value: 'value1');
  debugPrint('Write key1');
  
  result = await _encryptDbPlugin.read(
      key: 'key1', defaultValue: 'default_value');
  debugPrint('result2: $result');
  
  _encryptDbPlugin.write(key: 'key2', value: 'value2');
  debugPrint('Write key2');
  
  result = await _encryptDbPlugin.readAll();
  debugPrint('result3: $result');
  
  _encryptDbPlugin.clear(key: 'key1');
  debugPrint('Delete key1');
  
  result = await _encryptDbPlugin.readAll();
  debugPrint('result4: $result');
  
  _encryptDbPlugin.clearAll();
  debugPrint('Clear all');
}

重要提示

  • 此插件需要支持异步/等待。因此,您需要使用 Flutter 1.12.13+hotfix.5 或更高版本。
  • Android API 级别 28 或更高版本是必需的。
  • iOS 10.0 或更高版本是必需的。
  • Dart 3 已准备就绪。

特性和问题

请在 问题跟踪器 上提交功能请求和错误报告。

作者

Debojyoti Singha

贡献者

即将到来的功能

  • ❌ 可插拔数据库支持
  • ❌ 使用RSA-2048算法进行加密
  • ❌ macOS 支持
  • ❌ Windows 支持
  • ❌ Linux 支持

许可证

MIT License

Copyright (c) 2023 Debojyoti Singha

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

示例代码

import 'dart:async';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _encryptDbPlugin = EncryptDb();
  final Map<String, dynamic> _testPrintMap = {};

  [@override](/user/override)
  void initState() {
    super.initState();
    initialDb();
  }

  Future<void> initialDb() async {
    try {
      _encryptDbPlugin.initializeEncryptDb();
      _encryptDbPlugin.write(key: 'key0', value: 452);
    } catch (e) {
      debugPrint('Error: $e');
    }
  }

  void _runManualTest() async {
    try {
      var result = await _encryptDbPlugin.readAll();
      debugPrint('result0: $result');
      _testPrintMap['result0'] = result;
      await _encryptDbPlugin.clearAll();
      debugPrint('Clear all');
      result = await _encryptDbPlugin.readAll();
      debugPrint('result1: $result');
      _testPrintMap['result1'] = result;
      _encryptDbPlugin.write(key: 'key1', value: 'value1');
      debugPrint('Write key1');
      _testPrintMap['Write key1'] = 'Write key1';
      result = await _encryptDbPlugin.read(
          key: 'key1', defaultValue: 'default_value');
      debugPrint('result2: $result');
      _testPrintMap['result2'] = result;
      _encryptDbPlugin.write(key: 'key2', value: 'value2');
      debugPrint('Write key2');
      _testPrintMap['Write key2'] = 'Write key2';
      result = await _encryptDbPlugin.readAll();
      debugPrint('result3: $result');
      _testPrintMap['result3'] = result;
      _encryptDbPlugin.clear(key: 'key1');
      debugPrint('Delete key1');
      _testPrintMap['Delete key1'] = 'Delete key1';
      result = await _encryptDbPlugin.readAll();
      debugPrint('result4: $result');
      _testPrintMap['result4'] = result;
      _encryptDbPlugin.clearAll();
      debugPrint('Clear all');
      _testPrintMap['Clear all'] = 'Clear all';
    } catch (e) {
      debugPrint('Error: $e');
    } finally {
      debugPrint('Test print map: $_testPrintMap');
      setState(() {});
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Encrypt DB example app'),
        ),
        body: SafeArea(
          child: Column(
            children: [
              ListView.builder(
                shrinkWrap: true,
                itemCount: _testPrintMap.length,
                itemBuilder:
                    (BuildContext context, int index) {
                  final key = _testPrintMap.keys.elementAt(index);
                  final value = _testPrintMap[key];
                  return Container(
                    margin: const EdgeInsets.all(8),
                    child: Text('log: $key: $value'),
                  );
                },
              ),
              ElevatedButton(
                onPressed: () async {
                  _runManualTest();
                },
                child: const Text('Run Test'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter数据库加密插件encrypt_db的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据库加密插件encrypt_db的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用encrypt_db插件来实现数据库加密的一个基本示例。encrypt_db插件允许你使用SQLCipher来加密SQLite数据库。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  encrypt_db: ^latest_version  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

步骤 2: 初始化加密数据库

在你的Flutter应用中,你需要初始化并打开一个加密的数据库。以下是一个简单的示例:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Encrypt DB Example'),
        ),
        body: Center(
          child: EncryptDBExample(),
        ),
      ),
    );
  }
}

class EncryptDBExample extends StatefulWidget {
  @override
  _EncryptDBExampleState createState() => _EncryptDBExampleState();
}

class _EncryptDBExampleState extends State<EncryptDBExample> {
  EncryptDB? _db;

  @override
  void initState() {
    super.initState();
    _initDatabase();
  }

  Future<void> _initDatabase() async {
    String dbName = 'encrypted_database.db';
    String password = 'your_strong_password';  // 请使用一个强密码

    // 打开或创建一个加密数据库
    _db = await EncryptDB.openDatabase(dbName, password: password);

    // 示例:创建一个表并插入数据
    _db!.execute('''
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL
      )
    ''');

    // 插入数据
    _db!.rawInsert('INSERT INTO users (name) VALUES (?)', ['Alice']);

    // 查询数据
    List<Map<String, dynamic>> results = await _db!.query('users');
    print(results);

    setState(() {}); // 如果需要在UI中显示结果,可以在这里更新状态
  }

  @override
  Widget build(BuildContext context) {
    return Text('Database initialized and data inserted.');
  }

  @override
  void dispose() {
    _db?.close();
    super.dispose();
  }
}

说明

  1. 依赖添加:确保在你的pubspec.yaml文件中添加了encrypt_db依赖。
  2. 数据库初始化:在_initDatabase方法中,使用EncryptDB.openDatabase方法打开或创建一个加密的数据库。你需要提供数据库的名称和密码。
  3. 数据库操作:使用execute方法创建表,使用rawInsert方法插入数据,使用query方法查询数据。
  4. 资源清理:在dispose方法中关闭数据库连接,以释放资源。

注意事项

  • 确保使用强密码来保护你的数据库。
  • 在生产环境中,不要将密码硬编码在代码中,考虑使用环境变量或安全的密钥管理服务。
  • 处理数据库操作时,最好使用try-catch块来捕获并处理可能的异常。

这个示例演示了如何使用encrypt_db插件在Flutter应用中创建、插入和查询加密的SQLite数据库。根据你的需求,你可以进一步扩展这个示例,比如添加更多的表、执行更复杂的查询等。

回到顶部