Flutter密码哈希插件dargon2_flutter的使用

Flutter密码哈希插件dargon2_flutter的使用

插件介绍

dargon2_flutter 是一个用于Flutter应用程序中的密码哈希插件,它通过dart:ffi与iOS和Android进行集成。该插件在移动设备上使用Argon2的C语言参考实现(Argon2),这是Password Hash Competition的获胜者,在Web端则使用hash-wasm提供的WebAssembly Argon2实现。

特殊注意事项

Flutter版本低于2.8

如果你使用的Flutter版本低于2.8,或者在使用时遇到UnimplementedError错误,请在应用入口点(通常是main.dart文件中的main()函数)添加如下代码:

void main() {
  DArgon2Flutter.init();
  runApp(MyApp());
}

纯Objective-C iOS项目

对于使用纯Objective-C开发的iOS部分,需要创建一个Swift文件并选择创建桥接头文件,即使你不需要在这个Swift文件或桥接头文件中添加任何内容,但它们的存在对于插件的正确编译是必要的。

Linux桌面环境

在Linux环境下构建时,确保安装了C标准库。可以通过运行sudo apt install build-essential来安装(适用于基于Debian的系统)。如果未安装,底层的C实现将无法成功构建,进而导致级联构建失败。

使用示例

下面是一个完整的示例程序,演示如何使用dargon2_flutter进行密码哈希以及在Isolate中使用此插件。

import 'dart:convert';
import 'package:dargon2_flutter/dargon2_flutter.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  // 如果使用的是Flutter版本低于2.8,则需要初始化
  DArgon2Flutter.init();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  /// 定义控制器和hash字符串变量
  TextEditingController _passController = TextEditingController();
  TextEditingController _saltController = TextEditingController();
  String _base64Hash = "";
  String _hexHash = "";
  String _encodedString = "";

  /// 构建UI界面
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('dargon2_flutter example'),
        ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 30.0),
                child: TextField(
                  key: Key("hashEntry"),
                  controller: _passController,
                  decoration: InputDecoration(hintText: "Enter a value to hash"),
                ),
              ),
              SizedBox(height: 5),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 30.0),
                child: TextField(
                  key: Key("saltEntry"),
                  controller: _saltController,
                  decoration: InputDecoration(hintText: "Enter a salt (optional)"),
                ),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                key: Key("hash"),
                child: Text("Hash With Argon2"),
                onPressed: _hash,
              ),
              SizedBox(height: 10),
              Text(
                "Hash Values",
                style: Theme.of(context).textTheme.headline6,
              ),
              SizedBox(height: 10),
              Text(
                "Base64 Hash\n$_base64Hash",
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 10),
              Text(
                "Hex Hash\n$_hexHash",
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 10),
              Text(
                "Encoded String\n$_encodedString",
                key: Key("hashText"),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 执行哈希操作的方法
  void _hash() async {
    Salt salt = _saltController.text.isEmpty
        ? Salt.newSalt()
        : Salt(utf8.encode(_saltController.text));

    // 对给定文本进行哈希处理并显示结果
    DArgon2Result result =
        await argon2.hashPasswordString(_passController.text, salt: salt);
    setState(() {
      _base64Hash = result.base64String;
      _hexHash = result.hexString;
      _encodedString = result.encodedString;
    });

    // 调用Isolate中的哈希计算
    compute(hashWithArgon2Isolate, {"hashString": "Test hash string"});
  }
}

/// Isolate中使用的哈希方法
Future<void> hashWithArgon2Isolate(Map<String, String> map) async {
  DArgon2Flutter.init();
  DArgon2Result result =
      await argon2.hashPasswordString(map["hashString"]!, salt: Salt.newSalt());
  print("Hex String: ${result.hexString}");
  print("Base64 String: ${result.base64String}");
  print("Encoded String: ${result.encodedString}");
}

以上代码展示了如何在一个简单的Flutter应用中使用dargon2_flutter插件对用户输入的文本进行哈希处理,并展示了如何在Isolate中使用该插件以避免阻塞主线程。希望这个例子能够帮助你更好地理解和使用dargon2_flutter


更多关于Flutter密码哈希插件dargon2_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter密码哈希插件dargon2_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用dargon2_flutter插件进行密码哈希的示例代码。dargon2_flutter是一个Flutter插件,它基于Argon2哈希算法,提供了强大的密码哈希功能。

首先,确保你的Flutter项目已经创建并初始化。接下来,你需要在pubspec.yaml文件中添加dargon2_flutter依赖:

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

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

安装完成后,你可以在你的Flutter项目中使用以下代码进行密码哈希操作:

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

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

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

class PasswordHashDemo extends StatefulWidget {
  @override
  _PasswordHashDemoState createState() => _PasswordHashDemoState();
}

class _PasswordHashDemoState extends State<PasswordHashDemo> {
  final _formKey = GlobalKey<FormState>();
  String _password = '';
  String _salt = '';
  String _hash = '';
  String _verifyResult = '';

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Password is required';
                }
              },
              onSaved: (value) {
                _password = value;
              },
            ),
            TextFormField(
              decoration: InputDecoration(labelText: 'Salt (optional)'),
              validator: (value) {
                if (value.isEmpty) {
                  // If salt is empty, we will generate one later
                  return null;
                }
              },
              onSaved: (value) {
                _salt = value;
              },
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState!.save();

                  // If no salt is provided, generate one
                  if (_salt.isEmpty) {
                    _salt = await Argon2.generateSalt();
                  }

                  try {
                    _hash = await Argon2.hash(_password, _salt);
                    setState(() {});
                  } catch (e) {
                    // Handle hashing errors
                    print('Hashing error: $e');
                  }
                }
              },
              child: Text('Hash Password'),
            ),
            SizedBox(height: 20),
            Text('Hash: $_hash'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                try {
                  bool result = await Argon2.verify(_password, _hash);
                  setState(() {
                    _verifyResult = result ? 'Verification successful' : 'Verification failed';
                  });
                } catch (e) {
                  // Handle verification errors
                  print('Verification error: $e');
                }
              },
              child: Text('Verify Password'),
            ),
            SizedBox(height: 20),
            Text('Verification Result: $_verifyResult'),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何使用dargon2_flutter插件进行密码哈希和验证。主要步骤如下:

  1. 用户输入密码和可选的盐值。
  2. 如果用户没有提供盐值,则生成一个新的盐值。
  3. 使用提供的密码和盐值生成哈希。
  4. 显示生成的哈希值。
  5. 提供验证按钮,验证输入的密码是否与哈希值匹配。

注意:在实际应用中,盐的生成和存储需要谨慎处理,以确保安全性和随机性。这个示例仅用于演示目的,可能需要根据具体需求进行调整。

回到顶部