Flutter Windows凭证管理插件flutter_windows_vault的使用

Flutter Windows凭证管理插件flutter_windows_vault的使用

flutter_windows_vault 插件允许你在 Windows 凭证管理器(即 Windows Vault)中读写数据,并支持加密。

获取开始

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

dependencies:
  flutter:
    sdk: flutter
  flutter_windows_vault: ^版本号

然后运行 flutter pub get 来安装插件。

接下来是一些基本操作的示例代码:

import 'package:flutter_windows_vault/flutter_windows_vault.dart';

// 写入值
bool result = await FlutterWindowsVault.set(key: 'password', value: '123456789');

// 加密并写入值
bool result = await FlutterWindowsVault.set(key: 'password', value: '123456789', encrypted: true);

// 读取值
Cred cred = await FlutterWindowsVault.get(key: 'password');

// 读取加密值
Cred cred = await FlutterWindowsVault.get(key: 'password', encrypted: true);

// 删除值
bool result = await FlutterWindowsVault.del(key: 'password');

// 读取所有值
List<Cred> list = await FlutterWindowsVault.list();

// 加密数据
/// 结果加密: => @@D\u0007\b\f\n\rgAAAAAYppBAAAAAAA5c5uXGQ1pJpY0VrAG-aZawRYNC3MboXJ
String data = await FlutterWindowsVault.encrypt(value: '123456789');

// 解密数据
/// 结果解密: 数据 => '123456789'
String data = await FlutterWindowsVault.decrypt(value:"@@D\u0007\b\f\n\rgAAAAAYppBAAAAAAA5c5uXGQ1pJpY0VrAG-aZawRYNC3MboXJ");

具体写入数据

所有参数的详细文档可以参考以下链接: CREDENTIALA 结构

FlutterWindowsVault.set(
    /// key 或 TargetName: 凭证的名称。TargetName 和 Type 成员唯一标识凭证。创建凭证后,此成员不能更改。应删除旧名称的凭证,并用新名称创建一个。
    key: 'password',
    /// value: 凭证的秘密数据。value 成员可以读取和写入。
    value: '123456789',
    /// persist: 定义此凭证的持久性。此成员可以读取和写入。
    persist: Persist.CRED_PERSIST_LOCAL_MACHINE,
    /// type: 凭证的类型。创建凭证后,此成员不能更改。有效值如下。
    type: Type.CRED_TYPE_GENERIC,
    /// userName: 用于连接到 TargetName 的帐户的用户名。
    userName: 'com.example.<your_app_name>',
    /// encrypted: 是否在保存前加密数据。
    encrypted: true,
    /// fAsSelf: 设置为 TRUE 表示凭据在当前进程的安全上下文中加密。设置为 FALSE 表示凭据在调用线程的安全上下文中加密。
    fAsSelf: false,
);

对于更多关于 wincred.h API 的详细信息,可以参考以下链接: wincred.h 头文件

支持作者

如果您觉得这个插件对您有帮助,可以考虑通过以下方式支持作者:

Buy Me A Coffee

示例代码

以下是一个完整的示例代码,展示了如何使用 flutter_windows_vault 插件进行各种操作。

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert' show JsonEncoder;
import 'package:flutter/services.dart';
import 'package:flutter_windows_vault/flutter_windows_vault.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Page(),
    );
  }
}

class Page extends StatefulWidget {
  [@override](/user/override)
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  String _platformVersion = 'Unknown';
  static final jsonEncoder = JsonEncoder.withIndent('   ');

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

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await FlutterWindowsVault.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
    });
  }

  _showDialog({
    required String title,
    required dynamic value,
    List<dynamic> values: const [],
    bool error = false,
  }) {
    showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text('$title ${error ? 'error : ' : 'done : '}'),
            contentPadding: EdgeInsets.all(20),
            children: [
              IconButton(
                icon: Icon(
                  error ? Icons.error : Icons.done,
                  color: Colors.red,
                ),
                onPressed: Navigator.of(context).pop,
              ),
              if (value != null)
                SelectableText(
                  '${error ? value : jsonEncoder.convert(value)}',
                ),
              for (dynamic v in values)
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                  margin: EdgeInsets.only(top: 20),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.red, width: 2),
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: Text('${jsonEncoder.convert(v)}'),
                ),
            ],
          );
        });
  }

  void set() {
    FlutterWindowsVault.set(key: 'password', value: '123456789')
        .then((v) => _showDialog(title: 'set', value: v))
        .catchError(
            (err) => _showDialog(title: 'set', error: true, value: err));
  }

  void get() {
    FlutterWindowsVault.get(key: 'password')
        .then((v) => _showDialog(title: 'get', value: v?.toJson))
        .catchError(
            (err) => _showDialog(title: 'get', error: true, value: err));
  }

  void containsKey() {
    FlutterWindowsVault.containsKey(key: 'password')
        .then((v) => _showDialog(title: 'containsKey', value: v))
        .catchError(
            (err) => _showDialog(title: 'containsKey', error: true, value: err));
  }

  void del() {
    FlutterWindowsVault.del(key: 'password')
        .then((v) => _showDialog(title: 'del', value: v))
        .catchError(
            (err) => _showDialog(title: 'del', error: true, value: err));
  }

  void list() {
    FlutterWindowsVault.list()
        .then((v) => _showDialog(
              title: 'list',
              value: null,
              values: v.map((e) => e.toJson).toList(),
            ))
        .catchError(
            (err) => _showDialog(title: 'list', error: true, value: err));
  }

  void encrypt() {
    FlutterWindowsVault.encrypt(
      value: '123456789',
      fAsSelf: false,
    );
    FlutterWindowsVault.encrypt(value: '123456789')
        .then((v) => _showDialog(title: 'encrypt', value: v))
        .catchError(
            (err) => _showDialog(title: 'encrypt', error: true, value: err));
  }

  void decrypte() {
    FlutterWindowsVault.decrypt(
            value:
                "@@D\u0007\b\f\n\rgAAAAAYppBAAAAAAA5c5uXGQ1pJpY0VrAG-aZawRYNC3MboXJ")
        .then((v) => _showDialog(title: 'decrypte', value: v))
        .catchError(
            (err) => _showDialog(title: 'decrypte', error: true, value: err));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        drawer: Drawer(),
        body: Center(
          child: Container(
            constraints: BoxConstraints(
              maxWidth: 504,
              maxHeight: MediaQuery.of(context).size.height - 40,
            ),
            margin: EdgeInsets.symmetric(vertical: 20, horizontal: 40),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(height: 20),
                  Text('Running on: $_platformVersion\n'),
                  SizedBox(height: 20),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Set'),
                    onPressed: set,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Get'),
                    onPressed: get,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Contains Key'),
                    onPressed: containsKey,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Delete'),
                    onPressed: del,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('List'),
                    onPressed: list,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Encrypt'),
                    onPressed: encrypt,
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    minWidth: 504,
                    height: 60,
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: Text('Decrypt'),
                    onPressed: decrypte,
                  ),
                  SizedBox(height: 20),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter Windows凭证管理插件flutter_windows_vault的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Windows凭证管理插件flutter_windows_vault的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中管理Windows凭证可以使用 flutter_windows_vault 插件。这个插件允许你访问和管理Windows的凭证管理器(Credential Manager)。以下是如何使用 flutter_windows_vault 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_windows_vault: ^0.1.0  # 检查最新版本

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

2. 导入插件

在你的Dart文件中导入插件:

import 'package:flutter_windows_vault/flutter_windows_vault.dart';

3. 使用插件

flutter_windows_vault 插件提供了一些方法来管理Windows凭证,以下是常用的方法:

保存凭证

你可以使用 saveCredential 方法来保存凭证:

Future<void> saveCredential() async {
  try {
    await FlutterWindowsVault.saveCredential(
      targetName: 'MyApp',
      userName: 'myUsername',
      password: 'myPassword',
    );
    print('Credential saved successfully');
  } catch (e) {
    print('Failed to save credential: $e');
  }
}

获取凭证

你可以使用 getCredential 方法来获取保存的凭证:

Future<void> getCredential() async {
  try {
    final credential = await FlutterWindowsVault.getCredential(
      targetName: 'MyApp',
    );
    print('Username: ${credential.userName}');
    print('Password: ${credential.password}');
  } catch (e) {
    print('Failed to get credential: $e');
  }
}

删除凭证

你可以使用 deleteCredential 方法来删除保存的凭证:

Future<void> deleteCredential() async {
  try {
    await FlutterWindowsVault.deleteCredential(
      targetName: 'MyApp',
    );
    print('Credential deleted successfully');
  } catch (e) {
    print('Failed to delete credential: $e');
  }
}
回到顶部