Flutter椭圆曲线加密插件flutter_micro_ecc的使用

Flutter椭圆曲线加密插件flutter_micro_ecc的使用

flutter_micro_ecc 是一个用于 Flutter 应用的微椭圆曲线加密库。它支持多种椭圆曲线,并提供了生成密钥对和计算共享密钥的功能。

特性

曲线

  • SECP160R1
  • SECP192R1
  • SECP224R1
  • SECP256R1
  • SECP256K1

操作

  • 生成密钥对
  • 计算共享密钥

使用方法

选择曲线

final curve = EcdhCurve.SECP256R1;

生成密钥对

final Ecdh ecdh = Ecdh();
EcdhKeyPair _alice = _ecdh.generateKeyPair(_curve);

计算共享密钥

final Ecdh ecdh = Ecdh();
Uint8List _aliceSharedSecret = _ecdh.computeSharedSecret(_alice.privateKey, _bob.publicKey, _curve);

示例应用

以下是一个完整的示例应用,演示如何使用 flutter_micro_ecc 生成密钥对并计算共享密钥。

示例代码

import 'dart:typed_data';

import 'package:flutter/material.dart';

import 'package:flutter_micro_ecc/flutter_micro_ecc.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  EcdhKeyPair? _alice;
  EcdhKeyPair? _bob;

  Uint8List? _aliceSharedSecret;
  Uint8List? _bobSharedSecret;

  final _ecdh = Ecdh();
  final _curve = EcdhCurve.SECP256R1;

  void _generateAliceKeys() {
    _clearSharedSecret();
    setState(() {
      _alice = _ecdh.generateKeyPair(_curve);
    });
  }

  void _generateBobKeys() {
    _clearSharedSecret();
    setState(() {
      _bob = _ecdh.generateKeyPair(_curve);
    });
  }

  void _computeSharedSecret() {
    setState(() {
      _aliceSharedSecret = _ecdh.computeSharedSecret(
        _alice!.privateKey,
        _bob!.publicKey,
        _curve,
      );
      _bobSharedSecret = _ecdh.computeSharedSecret(
        _bob!.privateKey,
        _alice!.publicKey,
        _curve,
      );
    });
  }

  void _clearSharedSecret() {
    setState(() {
      _aliceSharedSecret = null;
      _bobSharedSecret = null;
    });
  }

  bool _keysEqual() {
    return _aliceSharedSecret?.toHex() == _bobSharedSecret?.toHex();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.purple,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('ECDH Keypair Generation'),
        ),
        body: SizedBox(
          height: double.infinity,
          child: SingleChildScrollView(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  UserKeyPairView(
                    name: "Alice",
                    keyPair: _alice,
                    sharedSecret: _aliceSharedSecret,
                    regenerate: _generateAliceKeys,
                  ),
                  UserKeyPairView(
                    name: "Bob",
                    keyPair: _bob,
                    sharedSecret: _bobSharedSecret,
                    regenerate: _generateBobKeys,
                  ),
                ],
              ),
            ),
          ),
        ),
        floatingActionButton:
            (_aliceSharedSecret == null || _bobSharedSecret == null)
                ? FloatingActionButton.extended(
                    label: const Text('Compute'),
                    onPressed: _computeSharedSecret,
                  )
                : FloatingActionButton(
                    onPressed: () {},
                    backgroundColor: _keysEqual() ? Colors.green : Colors.red,
                    child: _keysEqual()
                        ? const Icon(Icons.check)
                        : const Icon(
                            Icons.cancel,
                          ),
                  ),
      ),
    );
  }
}

class UserKeyPairView extends StatelessWidget {
  final String name;
  final EcdhKeyPair? keyPair;
  final Uint8List? sharedSecret;
  final Function regenerate;

  final _valueStyle = const TextStyle(
    fontSize: 12,
    fontWeight: FontWeight.w300,
    fontFamily: 'Source Code Pro',
  );

  const UserKeyPairView({
    Key? key,
    required this.name,
    required this.keyPair,
    required this.sharedSecret,
    required this.regenerate,
  }) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          ListTile(
            title: Text(name),
            trailing: TextButton.icon(
              onPressed: () => regenerate(),
              label: Text(keyPair == null ? "Generate" : "Re-Generate"),
              icon: const Icon(Icons.refresh),
            ),
          ),
          const Divider(),
          ListTile(
            leading: const Icon(Icons.lock, color: Colors.red),
            title: const Text("Private key"),
            subtitle: Text(
              keyPair?.privateKey.toHex().prettify() ?? "-",
              style: _valueStyle,
            ),
          ),
          ListTile(
            leading: const Icon(
              Icons.vpn_key,
              color: Colors.green,
            ),
            title: const Text("Public key"),
            subtitle: Text(
              keyPair?.publicKey.toHex().prettify() ?? "-",
              style: _valueStyle,
            ),
          ),
          ListTile(
            leading: Icon(
              sharedSecret == null
                  ? Icons.mark_email_unread_outlined
                  : Icons.mark_email_read_outlined,
              color: sharedSecret == null ? Colors.amber : Colors.blue,
            ),
            title: const Text("Shared Secret"),
            subtitle: Text(
              sharedSecret?.toHex().prettify() ?? "-",
              style: _valueStyle,
            ),
          ),
        ],
      ),
    );
  }
}

extension Uint8ListExtension on Uint8List {
  String toHex() {
    return map((e) => e.toRadixString(16).padLeft(2, '0')).join().toUpperCase();
  }
}

extension StringExtension on String {
  String prettify() {
    return replaceAllMapped(RegExp(r'(..)', multiLine: true), (match) {
      return '${match.group(1)} ';
    });
  }
}

更多关于Flutter椭圆曲线加密插件flutter_micro_ecc的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter椭圆曲线加密插件flutter_micro_ecc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_micro_ecc 是一个用于在 Flutter 应用中实现椭圆曲线加密(ECC)的插件。它基于微型椭圆曲线加密库(Micro-ECC),提供了轻量级的加密功能,适用于资源受限的设备。

安装

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

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

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

基本用法

flutter_micro_ecc 提供了以下几个主要功能:

  1. 生成密钥对
  2. 签名
  3. 验证签名
  4. 加密
  5. 解密

1. 生成密钥对

你可以使用 generateKeyPair 方法来生成一个椭圆曲线密钥对。

import 'package:flutter_micro_ecc/flutter_micro_ecc.dart';

void main() async {
  // 生成密钥对
  KeyPair keyPair = await FlutterMicroEcc.generateKeyPair();
  
  print('Private Key: ${keyPair.privateKey}');
  print('Public Key: ${keyPair.publicKey}');
}

2. 签名

使用 sign 方法对数据进行签名。

import 'package:flutter_micro_ecc/flutter_micro_ecc.dart';

void main() async {
  // 生成密钥对
  KeyPair keyPair = await FlutterMicroEcc.generateKeyPair();
  
  // 要签名的数据
  String data = 'Hello, World!';
  
  // 对数据进行签名
  String signature = await FlutterMicroEcc.sign(keyPair.privateKey, data);
  
  print('Signature: $signature');
}

3. 验证签名

使用 verify 方法验证签名。

import 'package:flutter_micro_ecc/flutter_micro_ecc.dart';

void main() async {
  // 生成密钥对
  KeyPair keyPair = await FlutterMicroEcc.generateKeyPair();
  
  // 要签名的数据
  String data = 'Hello, World!';
  
  // 对数据进行签名
  String signature = await FlutterMicroEcc.sign(keyPair.privateKey, data);
  
  // 验证签名
  bool isValid = await FlutterMicroEcc.verify(keyPair.publicKey, data, signature);
  
  print('Is Signature Valid: $isValid');
}

4. 加密与解密

flutter_micro_ecc 也支持使用 ECC 进行加密和解密操作。

import 'package:flutter_micro_ecc/flutter_micro_ecc.dart';

void main() async {
  // 生成密钥对
  KeyPair keyPair = await FlutterMicroEcc.generateKeyPair();
  
  // 要加密的数据
  String data = 'Hello, World!';
  
  // 使用公钥加密数据
  String encryptedData = await FlutterMicroEcc.encrypt(keyPair.publicKey, data);
  
  print('Encrypted Data: $encryptedData');
  
  // 使用私钥解密数据
  String decryptedData = await FlutterMicroEcc.decrypt(keyPair.privateKey, encryptedData);
  
  print('Decrypted Data: $decryptedData');
}
回到顶部