Flutter加密功能插件flutter_feature_crypto的使用

Flutter加密功能插件flutter_feature_crypto的使用

Flutter库flutter_feature_crypto提供了一种通过仓库实现的加密解决方案。该库通过结构化的仓库模式简化了处理加密函数(如加密、解密、哈希和数字签名)的过程。它旨在轻松集成到任何Flutter项目中,确保安全的数据处理和存储,同时具有灵活且可扩展的架构。

方法

AES

生成密钥

生成AES密钥。

final key = cryptoAESRepository.getKey(32);
参数名 类型 是否必需 描述
size int 可能的值为16、24或32。否则会抛出CoreCryptoException

获取初始化向量密钥

生成初始化向量密钥。

final ivKey = cryptoAESRepository.getIVKey();

加密

加密明文并返回base64编码。

final encrypted = cryptoAESRepository.encrypt(key: key, ivKey: ivKey, plainText: plainText);
参数名 类型 是否必需 描述
key string 生成密钥生成的密钥。
ivKey string 获取初始化向量密钥生成的向量密钥。
plainText string 要加密的文本。
mode AESMode AES加密模式,默认为AESMode.cbc

解密

解密加密后的文本。

final decrypted = cryptoAESRepository.decrypt(key: key, ivKey: ivKey, encryptedText: encrypted);
参数名 类型 是否必需 描述
key string 生成密钥生成的密钥。
ivKey string 获取初始化向量密钥生成的向量密钥。
encryptedText string 要解密的加密文本。
mode AESMode AES加密模式,默认为AESMode.cbc

RSA

生成密钥

生成RSA密钥。

final key = cryptoRSARepository.generateKey();

加密

加密明文并返回加密密钥。

final encrypted = cryptoRSARepository.encrypt(
  encodedPublicKey: key.publicKey,
  plainText: plainText,
  encoding: CoreCrytoRSAEncoding.pkcs1,
  digest: CoreCryptoRSADigest.sha256,
);
参数名 类型 是否必需 描述
encodedPublicKey string 生成密钥生成的公钥。
encoding CoreCrytoRSAEncoding -
plainText string 要加密的文本。
digest CoreCryptoRSADigest -

解密

解密加密后的文本。

final decrypted = cryptoRSARepository.decrypt(
  encodedPrivateKey: key.privateKey,
  encryptedText: encrypted,
  encoding: CoreCrytoRSAEncoding.pkcs1,
  digest: CoreCryptoRSADigest.sha256,
);
参数名 类型 是否必需 描述
encodedPrivateKey string 生成密钥生成的私钥。
encryptedText string 要解密的加密文本。
encoding CoreCrytoRSAEncoding -
digest CoreCryptoRSADigest -

生成签名

生成RSA签名。

final signature = cryptoRSARepository.generateSignature(encodedPrivateKey: key.privateKey, plainText: plainText);
参数名 类型 是否必需 描述
encodedPrivateKey string 生成密钥生成的私钥。
plainText string 要生成签名的文本。

验证签名

验证RSA签名。

final isSignatureVerified = cryptoRSARepository.verifySignature(
  encodedPublicKey: key.publicKey,
  encodedSignature: signature,
  plainText: plainText,
);
参数名 类型 是否必需 描述
encodedPublicKey string 生成密钥生成的公钥。
encodedSignature string 要验证的签名。
plainText string 要验证的文本。

ED25519

生成密钥

生成ED25519密钥。

final key = cryptoED25519Repository.generateKey();

生成签名

生成ED25519签名。

final signature =
cryptoED25519Repository.generateSignature(encodedPrivateKey: key.privateKey, plainText: plainText);
参数名 类型 是否必需 描述
encodedPrivateKey string 生成密钥生成的私钥。
plainText string 要生成签名的文本。

验证签名

验证ED25519签名。

final isSignatureVerified = cryptoED25519Repository.verifySignature(
  encodedPublicKey: key.publicKey,
  encodedSignature: signature,
  plainText: plainText,
);
参数名 类型 是否必需 描述
encodedPublicKey string 生成密钥生成的公钥。
encodedSignature string 要验证的签名。
plainText string 要验证的文本。

示例代码

以下是一个完整的示例代码,展示了如何在Flutter项目中使用flutter_feature_crypto插件。

import 'dart:developer';

import 'package:example/data/dto/model/feature_model.dart';
import 'package:example/presentation/widget/feature_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feature_crypto/flutter_feature_crypto.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Feature Crypto'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  late CryptoRSARepository cryptoRSARepository;
  late CryptoAESRepository cryptoAESRepository;
  late CryptoED25519Repository cryptoED25519Repository;
  List<FeatureModel> features = [
    FeatureModel(
      title: 'AES Encryption',
      desc: 'AES Encryption And Decryption',
      key: 'AES',
    ),
    FeatureModel(
      title: 'RSA Encryption',
      desc: 'RSA Encryption And Decryption',
      key: 'RSA',
    ),
    FeatureModel(
      title: 'ED25519 Encryption',
      desc: 'ED25519 Encryption And Decryption',
      key: 'ED25519',
    )
  ];

  [@override](/user/override)
  void initState() {
    super.initState();
    cryptoRSARepository = CryptoRSARepositoryImpl();
    cryptoAESRepository = CryptoAESRepositoryImpl();
    cryptoED25519Repository = CryptoED25519RepositoryIml();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Cryptography')),
      body: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        itemCount: features.length,
        itemBuilder: (_, index) {
          final feature = features[index];
          return GestureDetector(
            onTap: () async {
              switch (feature.key) {
                case "AES":
                  final key = cryptoAESRepository.getKey(32);
                  log("AES KEY: $key");
                  final ivKey = cryptoAESRepository.getIVKey();
                  log("IV KEY: $ivKey");
                  const plainText = 'Passw0rd!';
                  log("PLAIN TEXT: $plainText");
                  final encrypted = cryptoAESRepository.encrypt(key: key, ivKey: ivKey, plainText: plainText);
                  log("ENCRYPTED TEXT: $encrypted");
                  if (encrypted != null) {
                    final decrypted = cryptoAESRepository.decrypt(key: key, ivKey: ivKey, encryptedText: encrypted);
                    log("DECRYPTED TEXT: $decrypted");
                  }
                  break;
                case "RSA":
                  const plainText = "Passw0rd!";
                  log("PLAIN TEXT: $plainText");
                  final key = cryptoRSARepository.generateKey();
                  log("RSA PRIVATE KEY: ${key.privateKey}");
                  log("RSA PUBLIC KEY: ${key.publicKey}");
                  final encrypted = cryptoRSARepository.encrypt(
                    encodedPublicKey: key.publicKey,
                    plainText: plainText,
                    encoding: CoreCrytoRSAEncoding.pkcs1,
                    digest: CoreCryptoRSADigest.sha256,
                  );
                  log("ENCRYPTED TEXT: $encrypted");
                  if (encrypted != null) {
                    final decrypted = cryptoRSARepository.decrypt(
                      encodedPrivateKey: key.privateKey,
                      encryptedText: encrypted,
                      encoding: CoreCrytoRSAEncoding.pkcs1,
                      digest: CoreCryptoRSADigest.sha256,
                    );
                    log("DECRYPTED TEXT: $decrypted");
                  }

                  final signature = cryptoRSARepository.generateSignature(encodedPrivateKey: key.privateKey, plainText: plainText);
                  log("SIGNATURE: $signature");
                  if (signature != null) {
                    final isSignatureVerified = cryptoRSARepository.verifySignature(
                      encodedPublicKey: key.publicKey,
                      encodedSignature: signature,
                      plainText: plainText,
                    );
                    log("IS SIGNATURE VERIFIED: $isSignatureVerified");
                  }
                  break;
                case "ED25519":
                  const plainText = "Passw0rd!";
                  log("PLAIN TEXT: $plainText");
                  final key = cryptoED25519Repository.generateKey();
                  log("PRIVATE KEY: ${key.privateKey}");
                  log("PUBLIC KEY: ${key.publicKey}");
                  final signature =
                  cryptoED25519Repository.generateSignature(encodedPrivateKey: key.privateKey, plainText: plainText);
                  log("SIGNATURE: $signature");
                  if (signature != null) {
                    final isSignatureVerified = cryptoED25519Repository.verifySignature(
                      encodedPublicKey: key.publicKey,
                      encodedSignature: signature,
                      plainText: plainText,
                    );
                    log("IS SIGNATURE VERIFIED: $isSignatureVerified");
                  }
                  break;
              }
            },
            child: ItemFeatureWidget(feature: feature),
          );
        },
      ),
    );
  }
}

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

1 回复

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


flutter_feature_crypto 是一个用于在 Flutter 应用中实现加密功能的插件。它提供了多种加密算法和工具,帮助开发者轻松地在应用中进行数据加密和解密操作。以下是如何使用 flutter_feature_crypto 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_feature_crypto: ^1.0.0  # 请使用最新版本

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

2. 导入插件

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

import 'package:flutter_feature_crypto/flutter_feature_crypto.dart';

3. 使用加密功能

flutter_feature_crypto 提供了多种加密算法,例如 AES、RSA 等。以下是一些常见的使用示例:

AES 加密和解密

void aesExample() async {
  // 初始化 AES 加密器
  final aes = AESCrypto();

  // 设置密钥和 IV(初始化向量)
  final key = 'your-32-byte-key-here'; // 32字节的密钥
  final iv = 'your-16-byte-iv-here';   // 16字节的IV

  // 加密数据
  final plainText = 'Hello, World!';
  final encrypted = await aes.encrypt(plainText, key, iv);
  print('Encrypted: $encrypted');

  // 解密数据
  final decrypted = await aes.decrypt(encrypted, key, iv);
  print('Decrypted: $decrypted');
}

RSA 加密和解密

void rsaExample() async {
  // 初始化 RSA 加密器
  final rsa = RSACrypto();

  // 生成 RSA 密钥对
  final keyPair = await rsa.generateKeyPair();
  final publicKey = keyPair.publicKey;
  final privateKey = keyPair.privateKey;

  // 加密数据
  final plainText = 'Hello, World!';
  final encrypted = await rsa.encrypt(plainText, publicKey);
  print('Encrypted: $encrypted');

  // 解密数据
  final decrypted = await rsa.decrypt(encrypted, privateKey);
  print('Decrypted: $decrypted');
}

4. 处理异常

在使用加密功能时,可能会遇到各种异常情况,例如密钥长度不正确、加密失败等。建议在使用时添加异常处理:

try {
  final encrypted = await aes.encrypt(plainText, key, iv);
  print('Encrypted: $encrypted');
} catch (e) {
  print('Encryption failed: $e');
}
回到顶部