Flutter安全存储插件cipher_vault的使用

Flutter安全存储插件cipher_vault的使用

示例用法

最简单的示例是在两种状态下。我们不知道密码时,显示动画。我们知道密码时,显示一个最终会显示密码的动画。

CipherVault(
    secret: _isShowSecretBool ? 'cipher_vault' : null,
),

当密码在动画结束时显示时,我们可以使用可选择文本进行复制或使用我们的复制小部件。

CipherVault(
    secret: 'My Password',
    buttonCopy: YourButtonCopyWidget(),
),

您可以使用配置器微调动画。例如,调整动画速度或使用其他语言。检查lib中的示例。

CipherVault(
    secret: 'Мой секрет 3',
    textStyle: const TextStyle(fontSize: 18.0),
    config: CipherVaultConfig(
        alphabetCipherVault: myAlphabet,
        minLengthCipherVault: 10,
        maxLengthCipherVault: 20,
    ),
),

目前所有可用设置如下:

/// VaultConfig - 微调CipherVault
///
/// [alphabetCipherVault] - 可以组成秘密动画的符号
///
/// [minLengthCipherVault] - 最小秘密长度
///
/// [maxLengthCipherVault] - 最大秘密长度
///
/// [updateAnimationUpdate] - 动画小部件刷新率
///
/// [updatePasswordAnimationUpdate] - 密码显示动画小部件刷新率
///
/// [showAnimationFrequency] - 在对分类的秘密进行动画处理时,字符替换的频率。标准值为0.2
///
/// [showPasswordAnimationFrequency] - 在对秘密进行解密动画处理时,字符替换的频率。标准值为0.5
///
/// [countAttemp] - 密码解密时可能的替换次数。标准值为5
const CipherVaultConfig({
    required this.alphabetCipherVault,
    required this.minLengthCipherVault,
    required this.maxLengthCipherVault,
    required this.updateAnimationUpdate,
    required this.updatePasswordAnimationUpdate,
    required this.showAnimationFrequency,
    required this.showPasswordAnimationFrequency,
    required this.countAttemp,
});

更改日志

查看更改日志以获取所有发行说明。

维护者

Valerij Shishov Igor Molchanov

该库开放供问题和拉取请求。如果您有改进的想法或发现错误,欢迎贡献!

许可证

MIT许可证


完整示例Demo

以下是完整的示例代码,展示了如何使用cipher_vault插件来安全地存储和显示密码。

import 'package:cipher_vault/cipher_vault.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'CipherVault Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 您可以使用不同的字母表。
  static const String cyrillicAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
      'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ!@#%^&*()-_=+';
  late bool isShowSecret;
  late String? secret1;
  late String? secret2;
  late String? secret3;
  // 您可以创建、存储和修改Config使用copyWith和CopyWithClass
  late CipherVaultConfig config;

  [@override](/user/override)
  void initState() {
    secret1 = null;
    secret2 = null;
    secret3 = null;
    isShowSecret = true;
    config = const CipherVaultConfig(
      minLengthCipherVault: 10,
      maxLengthCipherVault: 22,
      showPasswordAnimationFrequency: 0.8,
    );
    super.initState();
  }

  Future<void> _getSecret() async {
    // 使用Future获取秘密
    await Future.delayed(
      const Duration(seconds: 1),
      () => setState(
        () {
          secret1 = isShowSecret ? 'My Secret 1' : null;
          secret2 = isShowSecret ? 'My Long Secret 2' : null;
          secret3 = isShowSecret ? 'Мой длинный секрет 3' : null;
          isShowSecret = !isShowSecret;
        },
      ),
    );
  }

  Future<void> _copyButtonSecret() async {
    Clipboard.setData(ClipboardData(text: secret1 ?? '')).then(
      (_) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('The text has been copied'),
          ),
        );
      },
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CipherVault Example'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              CipherVault(
                secret: secret1,
              ),
              CipherVault(
                secret: secret2,
                textStyle: const TextStyle(fontSize: 16.0),
                config: config,
                buttonCopy: IconButton(
                  padding: EdgeInsets.zero,
                  iconSize: 16,
                  onPressed: _copyButtonSecret,
                  icon: const Icon(Icons.copy),
                ),
              ),
              // 示例使用另一个字母表
              CipherVault(
                secret: secret3,
                textStyle: const TextStyle(fontSize: 18.0),
                config: config.copyWith(
                  alphabetCipherVault: cyrillicAlphabet,
                  countAttemp: 15,
                  showAnimationFrequency: 3.0,
                  updateAnimationUpdate: const Duration(milliseconds: 30),
                ),
                buttonCopy: IconButton(
                  padding: EdgeInsets.zero,
                  iconSize: 18,
                  onPressed: _copyButtonSecret,
                  icon: const Icon(Icons.copy),
                ),
              ),
              ElevatedButton(
                onPressed: _getSecret,
                child: const Text('Get Secret'),
              ),
            ],
          ).withPadding(const EdgeInsets.all(16.0)),
        ),
      ),
    );
  }
}

extension ColumnPadding on Column {
  Column withPadding(EdgeInsetsGeometry padding) {
    return Column(
      children: children
          .map((widget) => Padding(
                padding: padding,
                child: widget,
              ))
          .toList(),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用cipher_vault插件进行安全存储的示例代码。cipher_vault是一个用于在Flutter应用中安全存储敏感数据的插件,它基于密钥管理服务(Key Management Service, KMS)来加密和解密数据。

首先,确保你的Flutter项目中已经添加了cipher_vault依赖。在你的pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  cipher_vault: ^x.y.z  # 请替换为最新版本号

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

接下来,在你的Flutter应用中,你可以按照以下步骤使用cipher_vault进行安全存储:

  1. 初始化CipherVault

    在使用cipher_vault之前,你需要初始化它。这通常是在你的应用的入口点(比如main.dart)中完成的。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化CipherVault
  await CipherVault.init();

  runApp(MyApp());
}
  1. 存储数据

    使用CipherVault.store方法来存储加密的数据。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Cipher Vault Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              String key = 'mySecretKey';
              String value = 'mySecretValue';

              // 存储数据
              await CipherVault.store(key: key, value: value);

              print('Data stored successfully!');
            },
            child: Text('Store Data'),
          ),
        ),
      ),
    );
  }
}
  1. 读取数据

    使用CipherVault.retrieve方法来读取之前存储的加密数据。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Cipher Vault Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  String key = 'mySecretKey';
                  String value = 'mySecretValue';

                  // 存储数据
                  await CipherVault.store(key: key, value: value);

                  print('Data stored successfully!');
                },
                child: Text('Store Data'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  String key = 'mySecretKey';

                  // 读取数据
                  String? retrievedValue = await CipherVault.retrieve(key: key);

                  if (retrievedValue != null) {
                    print('Retrieved Value: $retrievedValue');
                  } else {
                    print('No value found for key: $key');
                  }
                },
                child: Text('Retrieve Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  1. 删除数据

    使用CipherVault.delete方法来删除存储的数据。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Cipher Vault Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  String key = 'mySecretKey';
                  String value = 'mySecretValue';

                  // 存储数据
                  await CipherVault.store(key: key, value: value);

                  print('Data stored successfully!');
                },
                child: Text('Store Data'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  String key = 'mySecretKey';

                  // 读取数据
                  String? retrievedValue = await CipherVault.retrieve(key: key);

                  if (retrievedValue != null) {
                    print('Retrieved Value: $retrievedValue');
                  } else {
                    print('No value found for key: $key');
                  }
                },
                child: Text('Retrieve Data'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  String key = 'mySecretKey';

                  // 删除数据
                  await CipherVault.delete(key: key);

                  print('Data deleted successfully!');
                },
                child: Text('Delete Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中使用cipher_vault插件来安全地存储、读取和删除敏感数据。请根据你的具体需求调整代码。

回到顶部