Flutter加密解密插件rusty_chacha_dart的使用

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

Flutter加密解密插件rusty_chacha_dart的使用


Build Status Github Stars MIT License

Rusty ChaCha Banner

Rusty ChaCha 💃🦀

一个用于快速ChaCha20-Poly1305加密的Flutter库,利用了Rust chacha20poly1305库的能力。

🚧 开发中:目前不推荐在生产环境中使用。 🚧


特性

  • 使用ChaCha20-Poly1305加密和解密数据(带认证)
  • 支持额外认证数据(AAD)
  • 可选压缩功能,使用zstd

极速运行 🔥

多亏了Rust的加密和解密,使用ChaCha20-Poly1305的速度可以达到500-1000 MiB/s。这比诸如cryptography_flutterpointycastle等包快多达50倍

开始使用

在Flutter项目中,运行以下命令添加依赖:

flutter pub add rusty_chacha

使用示例

以下是使用rusty_chacha_dart进行加密和解密的完整示例:

import 'dart:typed_data';
import 'package:collection/collection.dart';
import 'package:rusty_chacha_dart/rusty_chacha_dart.dart';

void main() async {
  // 要加密的数据
  final data = Uint8List.fromList([1, 2, 3, 4, 5]);
  print('原始数据: $data');

  // 创建并使用一个带有随机密钥的ChaCha20Poly1305加密器
  RustyChaCha20Poly1305 cipher = await RustyChaCha.create();
  Uint8List encrypted = await cipher.encrypt(cleartext: data);
  print('加密后的数据: $encrypted');

  // 解密数据
  Uint8List decrypted = await cipher.decrypt(ciphertext: encrypted);
  print('解密后的数据: $decrypted');

  // 验证解密是否正确
  assert(const ListEquality().equals(data, decrypted));
}

// 使用指定密钥创建加密器
void useExplicitKey() async {
  // 生成密钥
  Uint8List key = await RustyChaCha20Poly1305.generateKey();
  cipher = await RustyChaCha.create(key: key);

  // 加密数据
  Uint8List encrypted = await cipher.encrypt(cleartext: data);
  print('使用指定密钥加密后的数据: $encrypted');

  // 解密数据
  Uint8List decrypted = await cipher.decrypt(ciphertext: encrypted);
  print('使用指定密钥解密后的数据: $decrypted');

  // 验证解密是否正确
  assert(const ListEquality().equals(data, decrypted));
}

// 压缩示例
void useCompression() async {
  // 如果加密时使用了压缩,则解密时也必须设置压缩
  cipher = await RustyChaCha.create(
    key: key,
    compression: const Compression.zstd(compressionLevel: 3), // 中等压缩级别
  );
  Uint8List compressedAndEncrypted = await cipher.encrypt(cleartext: data);
  print('压缩并加密后的数据: $compressedAndEncrypted');

  // 解密数据
  Uint8List decrypted = await cipher.decrypt(ciphertext: compressedAndEncrypted);
  print('解密后的数据: $decrypted');

  // 验证解密是否正确
  assert(const ListEquality().equals(data, decrypted));
}

// AAD示例
void useAad() async {
  // 额外的非敏感数据
  Uint8List additionalData = Uint8List.fromList([1, 2, 3]);
  cipher = await RustyChaCha.create();
  Uint8List encryptedWithAad = await cipher.encrypt(
    cleartext: data,
    aad: additionalData, // 在加密时传递
  );
  print('带有AAD的加密数据: $encryptedWithAad');

  // 解密数据
  Uint8List decrypted = await cipher.decrypt(
    ciphertext: encryptedWithAad,
    aad: additionalData, // 在解密时传递
  );
  print('带有AAD的解密数据: $decrypted');

  // 验证解密是否正确
  assert(const ListEquality().equals(data, decrypted));
}

// 使用XChaCha20Poly1305加密器
void useXChaCha20Poly1305() async {
  // 创建并使用一个XChaCha20Poly1305加密器,具有扩展的192位(24字节)nonce
  RustyXChaCha20Poly1305 cipherX = await RustyChaCha.createX();
  Uint8List encrypted = await cipherX.encrypt(cleartext: data);
  print('使用XChaCha20Poly1305加密后的数据: $encrypted');

  // 解密数据
  Uint8List decrypted = await cipherX.decrypt(ciphertext: encrypted);
  print('使用XChaCha20Poly1305解密后的数据: $decrypted');

  // 验证解密是否正确
  assert(const ListEquality().equals(data, decrypted));
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用rusty_chacha_dart插件进行加密和解密的示例代码。rusty_chacha_dart是一个使用Rust实现的ChaCha20加密算法的Dart封装库。

1. 添加依赖

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

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

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

2. 导入库并初始化

在你的Dart文件中导入rusty_chacha_dart库:

import 'package:rusty_chacha_dart/rusty_chacha_dart.dart';

3. 加密和解密示例

以下是一个简单的加密和解密示例:

void main() {
  // 密钥和初始向量(IV),必须是32字节长(256位)
  final Uint8List key = Uint8List.fromList(List.generate(32, (index) => index % 256));
  final Uint8List iv = Uint8List.fromList(List.generate(12, (index) => index % 256));

  // 需要加密的明文
  final String plaintext = 'Hello, Flutter and ChaCha20!';
  final Uint8List plaintextBytes = Uint8List.fromList(plaintext.codeUnits);

  // 加密
  final ChaCha20 chacha20 = ChaCha20(key: key, iv: iv);
  final Uint8List ciphertext = chacha20.encrypt(plaintextBytes);
  print('Ciphertext: ${ciphertext.map((e) => e.toRadixString(16).padLeft(2, '0')).join()}');

  // 解密
  final Uint8List decryptedBytes = chacha20.decrypt(ciphertext);
  final String decryptedText = String.fromCharCodes(decryptedBytes);
  print('Decrypted text: $decryptedText');
}

4. 完整示例

以下是一个完整的Flutter应用示例,该应用包含一个按钮,用于触发加密和解密操作,并在屏幕上显示结果:

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

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

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

class _MyAppState extends State<MyApp> {
  String _plaintext = 'Hello, Flutter and ChaCha20!';
  String _ciphertext = '';
  String _decryptedText = '';

  void _encryptAndDecrypt() {
    // 密钥和初始向量(IV),必须是32字节和12字节长
    final Uint8List key = Uint8List.fromList(List.generate(32, (index) => index % 256));
    final Uint8List iv = Uint8List.fromList(List.generate(12, (index) => index % 256));

    // 转换明文为字节数组
    final Uint8List plaintextBytes = Uint8List.fromList(_plaintext.codeUnits);

    // 创建ChaCha20实例并加密
    final ChaCha20 chacha20 = ChaCha20(key: key, iv: iv);
    final Uint8List ciphertextBytes = chacha20.encrypt(plaintextBytes);
    setState(() {
      _ciphertext = ciphertextBytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join();
    });

    // 解密
    final Uint8List decryptedBytes = chacha20.decrypt(ciphertextBytes);
    setState(() {
      _decryptedText = String.fromCharCodes(decryptedBytes);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ChaCha20 Encryption/Decryption'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text('Plaintext: $_plaintext'),
              SizedBox(height: 16),
              Text('Ciphertext: $_ciphertext'),
              SizedBox(height: 16),
              Text('Decrypted text: $_decryptedText'),
              SizedBox(height: 24),
              ElevatedButton(
                onPressed: _encryptAndDecrypt,
                child: Text('Encrypt and Decrypt'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,当你点击按钮时,应用将加密明文并显示密文,然后解密密文并显示解密后的文本。

希望这个示例对你有所帮助!如果有其他问题,请随时提问。

回到顶部