Flutter 3DES加密插件dart_3des的使用

Flutter 3DES加密插件dart_3des的使用

Triple DES 和 DES 块密码实现,源自CryptoJS。

此项目是从CryptoJS移植过来的。最新版本可以在 bryx/cryptojssytelus/CryptoJS 找到。

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  dart_3des: 1.0.0

如果在 Flutter 中:

  1. 运行 flutter pub get

如果在 Dart 中:

  1. 运行 dart pub get

示例

下面是一个简单的示例,展示了如何使用 dart_3des 插件进行3DES加密和解密。

示例代码

import 'package:dart_3des/dart_3des.dart';

void main() {
  // 设置密钥
  var key = "cipher"; // 密钥必须为8字节长
  
  // 创建BlockCipher对象
  var blockCipher = new BlockCipher(new DESEngine(), key);
  
  // 要加密的消息
  var message = "Uganda is a really difficult country";
  
  // 加密消息
  var ciphertext = blockCipher.encodeB64(message);
  
  // 解密消息
  var decoded = blockCipher.decodeB64(ciphertext);

  // 打印结果
  print("密钥: $key");
  print("明文: $message");
  print("密文(Base64): $ciphertext");
  print("解密后的密文: $decoded");
}

代码解释

  1. 导入库

    import 'package:dart_3des/dart_3des.dart';
    

    这里导入了 dart_3des 库,以便我们可以使用其中的加密功能。

  2. 设置密钥

    var key = "cipher";
    

    密钥长度必须为8字节。

  3. 创建BlockCipher对象

    var blockCipher = new BlockCipher(new DESEngine(), key);
    

    使用 DESEngine 和密钥创建一个 BlockCipher 对象。

  4. 要加密的消息

    var message = "Uganda is a really difficult country";
    

    这是要加密的原始字符串。

  5. 加密消息

    var ciphertext = blockCipher.encodeB64(message);
    

    使用 encodeB64 方法将消息加密并返回Base64编码的密文。

  6. 解密消息

    var decoded = blockCipher.decodeB64(ciphertext);
    

    使用 decodeB64 方法将密文解码回原始消息。

  7. 打印结果

    print("密钥: $key");
    print("明文: $message");
    print("密文(Base64): $ciphertext");
    print("解密后的密文: $decoded");
    

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

1 回复

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


当然,以下是如何在Flutter应用中使用dart_3des插件进行3DES加密和解密的示例代码。首先,你需要确保你的Flutter项目中已经添加了dart_3des依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  dart_3des: ^1.0.0  # 请检查最新版本号

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

接下来是一个简单的Flutter应用示例,展示如何使用dart_3des进行3DES加密和解密:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '3DES Encryption Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _plainTextController = TextEditingController();
  final TextEditingController _keyController = TextEditingController();
  final TextEditingController _encryptedTextController = TextEditingController();
  final TextEditingController _decryptedTextController = TextEditingController();

  String? _encryptedText;
  String? _decryptedText;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('3DES Encryption Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              controller: _plainTextController,
              decoration: InputDecoration(labelText: 'Plain Text'),
              maxLines: 4,
            ),
            SizedBox(height: 16),
            TextField(
              controller: _keyController,
              decoration: InputDecoration(labelText: 'Key (24 bytes)'),
              maxLength: 24,
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                _encryptText();
              },
              child: Text('Encrypt'),
            ),
            SizedBox(height: 16),
            TextField(
              controller: _encryptedTextController,
              decoration: InputDecoration(labelText: 'Encrypted Text'),
              readOnly: true,
              maxLines: 4,
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                _decryptText();
              },
              child: Text('Decrypt'),
            ),
            SizedBox(height: 16),
            TextField(
              controller: _decryptedTextController,
              decoration: InputDecoration(labelText: 'Decrypted Text'),
              readOnly: true,
              maxLines: 4,
            ),
          ],
        ),
      ),
    );
  }

  void _encryptText() {
    final plainText = _plainTextController.text;
    final key = _keyController.text.padRight(24).substring(0, 24); // Ensure key is 24 bytes long

    if (plainText.isEmpty || key.isEmpty || key.length != 24) {
      _showSnackBar('Plain text and key are required, and key must be 24 bytes.');
      return;
    }

    final TripleDES tripleDES = TripleDES(KeyParameter(Uint8List.fromList(key.codeUnits)));
    final encrypted = tripleDES.encrypt(plainText.codeUnits);
    final base64Encrypted = base64Encode(encrypted);

    setState(() {
      _encryptedText = base64Encrypted;
      _encryptedTextController.text = base64Encrypted;
      _decryptedText = null;
      _decryptedTextController.text = '';
    });
  }

  void _decryptText() {
    final encryptedTextBase64 = _encryptedTextController.text;
    final key = _keyController.text.padRight(24).substring(0, 24); // Ensure key is 24 bytes long

    if (encryptedTextBase64.isEmpty || key.isEmpty || key.length != 24) {
      _showSnackBar('Encrypted text and key are required, and key must be 24 bytes.');
      return;
    }

    final encryptedText = base64Decode(encryptedTextBase64);
    final TripleDES tripleDES = TripleDES(KeyParameter(Uint8List.fromList(key.codeUnits)));
    final decrypted = tripleDES.decrypt(encryptedText);

    setState(() {
      _decryptedText = String.fromCharCodes(decrypted);
      _decryptedTextController.text = _decryptedText!;
    });
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
  }
}

代码说明:

  1. 依赖添加:在pubspec.yaml中添加dart_3des依赖。
  2. UI构建:使用TextFieldElevatedButton构建了一个简单的UI,允许用户输入明文、密钥,并显示加密和解密后的文本。
  3. 加密函数_encryptText函数将明文和密钥转换为Uint8List,然后使用TripleDES类进行加密,并将结果转换为Base64编码字符串。
  4. 解密函数_decryptText函数将Base64编码的加密字符串解码回Uint8List,然后使用相同的密钥进行解密。
  5. 错误处理:简单的错误处理,确保密钥长度为24字节,并提示用户输入必要的字段。

这个示例展示了如何在Flutter中使用dart_3des插件进行3DES加密和解密。你可以根据需要对代码进行扩展或修改。

回到顶部