Flutter数据加密解密插件encryption_decryptions的使用

Flutter数据加密解密插件encryption_decryptions的使用

平台支持

Android iOS

注意事项

强制步骤(仅限Android)

在您的android > app > src > main > AndroidManifest.xml文件中。请在application标签内添加以下行:

tools:replace="android:label"

同时在manifest标签中添加:

xmlns:tools="http://schemas.android.com/tools"

如果您忘记添加这些,将会导致构建错误。

注意

确保您要加密的请求不应包含任何空值,并且您要解密的响应也不应包含空值。

高亮

  • 使用了rncryptor原生依赖以实现快速执行。
  • 加密或解密大数据仅需大约50毫秒
  • 每次加密相同的数据都会产生不同的输出,因此很难预测信息内容。

使用方法

以下是一个完整的示例演示如何使用encryption_decryptions插件进行数据加密和解密:

import 'dart:convert';

import 'package:encryption_decryptions/encryption_decryptions.dart';
import 'package:flutter/material.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> {
  final String enctyptDectyptkey = "hnbTojntU7u";
  final EncryptionDecryptions _encryptionDecryptions = EncryptionDecryptions();
  final Map<dynamic, dynamic> mockData = {
    "name": "John",
    "surname": "Doe",
    "age": 22,
    "hobies": ["Swimming", "football"]
  };
  final String mockPlain = "I am dev";

  String encryptedPlainText = "", displayPlaint = "";

  _encryptData({required String key, required String data}) async {
    return await _encryptionDecryptions.encrypt(data: data, key: key) ?? "";
  }

  _decryptData({required String key, required String data}) async {
    return await _encryptionDecryptions.decrypt(data: data, key: key) ?? "";
  }

  String encryptedJsonData = "", displayJsonData = "";

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Enctypt Decrypt',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Secure App'),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 18),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.grey[200]!,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        encryptedJsonData,
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 20),
                      const Divider(),
                      Text(
                        displayJsonData,
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                      ),
                      const SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          FilledButton(
                            onPressed: () async {
                              /// 将数据编码为JSON格式后再进行加密
                              encryptedJsonData = await _encryptData(key: enctyptDectyptkey, data: jsonEncode(mockData));
                              setState(() {});
                            },
                            child: const Text('Encrypt Json Data'),
                          ),
                          FilledButton(
                            onPressed: () async {
                              displayJsonData = await _decryptData(key: enctyptDectyptkey, data: encryptedJsonData);
                              setState(() {});
                            },
                            child: const Text('Decrypt Json Data'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
                const SizedBox(height: 50),
                Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.grey[200]!,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        encryptedPlainText,
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 20),
                      const Divider(),
                      Text(
                        displayPlaint,
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                      ),
                      const SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          FilledButton(
                            onPressed: () async {
                              /// 加密纯文本
                              encryptedPlainText = await _encryptData(key: enctyptDectyptkey, data: mockPlain);
                              setState(() {});
                            },
                            child: const Text('Encrypt Plain Text'),
                          ),
                          FilledButton(
                            onPressed: () async {
                              displayPlaint = await _decryptData(key: enctyptDectyptkey, data: encryptedPlainText);
                              setState(() {});
                            },
                            child: const Text('Decrypt Plain Text'),
                          ),
                        ],
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用encryption_decryptions插件进行数据加密和解密的示例代码。这个插件通常用于对敏感数据进行加密和解密,比如用户密码、API密钥等。

首先,确保你已经在pubspec.yaml文件中添加了encryption_decryptions依赖:

dependencies:
  flutter:
    sdk: flutter
  encryption_decryptions: ^x.y.z  # 请将x.y.z替换为最新版本号

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

接下来,下面是一个完整的示例,展示了如何使用这个插件进行加密和解密:

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

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

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

class _MyAppState extends State<MyApp> {
  final _controller = TextEditingController();
  String _encryptedData = '';
  String _decryptedData = '';
  String _key = 'your-secret-key'; // 密钥应该安全存储,这里仅为示例

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Encryption Decryption Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              TextField(
                controller: _controller,
                decoration: InputDecoration(labelText: 'Enter text to encrypt'),
                maxLines: 4,
              ),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    _encryptedData = EncryptionDecryption.encrypt(
                      plainText: _controller.text,
                      key: _key,
                    );
                    _decryptedData = ''; // 清空解密后的文本
                  });
                },
                child: Text('Encrypt'),
              ),
              SizedBox(height: 8),
              Text('Encrypted Data: $_encryptedData'),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    _decryptedData = EncryptionDecryption.decrypt(
                      cipherText: _encryptedData,
                      key: _key,
                    );
                  });
                },
                child: Text('Decrypt'),
              ),
              SizedBox(height: 8),
              Text('Decrypted Data: $_decryptedData'),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

在这个示例中:

  1. 我们创建了一个Flutter应用,包含一个文本输入字段和两个按钮(一个用于加密,一个用于解密)。
  2. 使用EncryptionDecryption.encrypt方法对输入的文本进行加密,使用指定的密钥。
  3. 使用EncryptionDecryption.decrypt方法对加密后的文本进行解密。

请注意,密钥(_key)在实际应用中应该安全存储,而不是硬编码在代码中。你可以考虑使用Keychain、Keystore或其他安全存储机制来管理密钥。

此外,encryption_decryptions插件可能使用某种加密算法(如AES),但具体实现细节取决于插件的内部逻辑。如果你需要特定的加密算法或有其他安全要求,请确保阅读插件的文档,并考虑使用更专业的加密库。

回到顶部