Flutter RSA加密解密插件simple_rsa3的使用

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

Flutter RSA加密解密插件simple_rsa3的使用

注意事项

本插件是original simple_rsa包的一个分支,所有功劳归于其原始作者。之前还有一个simple_rsa2版本,是我供职于DevelSystems时维护的,但由于那个项目的开发停滞了,我决定再次对其进行分叉,并让这个库重获新生。

简单RSA加密

这是一个用于使用公钥和私钥加密、解密(RSA/ECB/PKCS1)、验证和签名字符串的Flutter插件。

支持ANDOID和iOS平台(感谢adlanarifzr)。

安装

要在项目中使用该插件,请将simple_rsa3添加为pubspec.yaml文件中的依赖项。

dependencies:
  simple_rsa3: ^最新版本号

使用方法

首先,初始化公钥和私钥。最好以BASE64格式提供。

final publicKey = '...';
final privateKey = '...';

之后,您可以加密或解密文本:

final simple_rsa3 = SimpleRsa3();
final plainText = 'something';
final encryptedText = await simple_rsa3.encryptString(plainText, utf8.decode(base64.decode(publicKey))) ?? '';
final decryptedText = await simple_rsa3.decryptString(encryptedText, utf8.decode(base64.decode(privateKey))) ?? '';

// 测试
print(plainText == decryptedText ? 'true' : 'false');

或者,您可以签名并验证文本:

final simple_rsa3 = SimpleRsa3();
final plainText = 'something';
final signedText = await simple_rsa3.encryptString(plainText, utf8.decode(base64.decode(privateKey))) ?? '';
final verified = await simple_rsa3.verifyString(plainText, signedText, utf8.decode(base64.decode(publicKey))) ?? '';

// 测试
print(verified ? 'true' : 'false');

示例代码

以下是一个完整的示例,展示了如何在Flutter应用中使用simple_rsa3插件进行RSA加密和解密。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:simple_rsa3/simple_rsa3.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> {
  final _simpleRsa3Plugin = SimpleRsa3();

  final PUBLIC_KEY =
      "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBuAGGBgg9nuf6D2c5AIHc8" +
          "vZ6KoVwd0imeFVYbpMdgv4yYi5obtB/VYqLryLsucZLFeko+q1fi871ZzGjFtYXY" +
          "9Hh1Q5e10E5hwN1Tx6nIlIztrh5S9uV4uzAR47k2nng7hh6vuZ33kak2hY940RSL" +
          "H5l9E5cKoUXuQNtrIKTS4kPZ5IOUSxZ5xfWBXWoldhe+Nk7VIxxL97Tk0BjM0fJ3" +
          "8rBwv3++eAZxwZoLNmHx9wF92XKG+26I+gVGKKagyToU/xEjIqlpuZ90zesYdjV+" +
          "u0iQjowgbzt3ASOnvJSpJu/oJ6XrWR3egPoTSx+HyX1dKv9+q7uLl6pXqGVVNs+/" +
          "AgMBAAE=";

  final PRIVATE_KEY =
      "MIIEoQIBAAKCAQBuAGGBgg9nuf6D2c5AIHc8vZ6KoVwd0imeFVYbpMdgv4yYi5ob" +
          "tB/VYqLryLsucZLFeko+q1fi871ZzGjFtYXY9Hh1Q5e10E5hwN1Tx6nIlIztrh5S" +
          "9uV4uzAR47k2nng7hh6vuZ33kak2hY940RSLH5l9E5cKoUXuQNtrIKTS4kPZ5IOU" +
          "SxZ5xfWBXWoldhe+Nk7VIxxL97Tk0BjM0fJ38rBwv3++eAZxwZoLNmHx9wF92XKG" +
          "+26I+gVGKKagyToU/xEjIqlpuZ90zesYdjV+u0iQjowgbzt3ASOnvJSpJu/oJ6Xr" +
          "WR3egPoTSx+HyX1dKv9+q7uLl6pXqGVVNs+/AgMBAAECggEANG9qC1n8De3TLPa+" +
          "IkNXk1SwJlUUnAJ6ZCi3iyXZBH1Kf8zMATizk/wYvVxKHbF1zTyl94mls0GMmSmf" +
          "J9+Hlguy//LgdoJ9Wouc9TrP7BUjuIivW8zlRc+08lIjD64qkfU0238XldORXbP8" +
          "2BKSQF8nwz97WE3YD+JKtZ4x83PX7hqC9zabLFIwFIbmJ4boeXzj4zl8B7tjuAPq" +
          "R3JNxxKfvhpqPcGFE2Gd67KJrhcH5FIja4H/cNKjatKFcP6qNfCA7e+bua6bL0Cy" +
          "DzmmNSgz6rx6bthcJ65IKUVrJK6Y0sBcNQCAjqZDA0Bs/7ShGDL28REuCS1/udQz" +
          "XyB7gQKBgQCrgy2pvqLREaOjdds6s1gbkeEsYo7wYlF4vFPg4sLIYeAt+ed0kn4N" +
          "dSmtp4FXgGyNwg7WJEveKEW7IEAMQBSN0KthZU4sK9NEu2lW5ip9Mj0uzyUzU4lh" +
          "B+zwKzZCorip/LIiOocFWtz9jwGZPCKC8expUEbMuU1PzlxrytHJaQKBgQCkMEci" +
          "EHL0KF5mcZbQVeLaRuecQGI5JS4KcCRab24dGDt+EOKYchdzNdXdM8gCHNXb8RKY" +
          "NYnHbCjheXHxV9Jo1is/Qi9nND5sT54gjfrHMKTWAtWKAaX55qKG0CEyBB87WqJM" +
          "Ydn7i4Rf0rsRNa1lbxQ+btX14d0xol9313VC5wKBgERD6Rfn9dwrHivAjCq4GXiX" +
          "vr0w2V3adD0PEH+xIgAp3NXP4w0mBaALozQoOLYAOrTNqaQYPE5HT0Hk2zlFBClS" +
          "BfS1IsE4DFYOFiZtZDoClhGch1z/ge2p/ue0+1rYc5HNL4WqL/W0rcMKeYNpSP8/" +
          "lW5xckyn8Jq0M1sAFjIJAoGAQJvS0f/BDHz6MLvQCelSHGy8ZUscm7oatPbOB1xD" +
          "62UGvCPu1uhGfAqaPrJKqTIpoaPqmkSvE+9m4tsEUGErph9o4zqrJqRzT/HAmrTk" +
          "Ew/8PU7eMrFVW9I68GvkNCdVFukiZoY23fpXu9FT1YDW28xrHepFfb1EamynvqPl" +
          "O88CgYAvzzSt+d4FG03jwObhdZrmZxaJk0jkKu3JkxUmav9Zav3fDTX1hYxDNTLi" +
          "dazvUFfqN7wqSSPqajQmMoTySxmLI8gI4qC0QskB4lT1A8OfmjcDwbUzQGam5Kpz" +
          "ymmKJA9DgQpPgEIjHAnw2dUDR+wI/Loywb0AGLIbszseCOlc2Q==";

  final myController = TextEditingController();
  String _stringEncoded = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  [@override](/user/override)
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  // 平台消息是异步的,所以我们初始化在异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch处理PlatformException。
    // 我们也处理消息可能返回null的情况。
    try {
      platformVersion = 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果小部件从树中移除而异步平台消息还在飞行中,我们想要丢弃回复而不是调用setState来更新我们的非存在外观。
    if (!mounted) return;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  controller: myController,
                  decoration: const InputDecoration(
                    hintText: "写入要加密的文本",
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  ElevatedButton(
                    onPressed: () async {
                      String tmp = "";
                      try {
                        if (_stringEncoded.isEmpty) {
                          final text = myController.text;
                          if (text.isNotEmpty) {
                            final tmp = await _simpleRsa3Plugin.encryptString(
                                    myController.text, PUBLIC_KEY) ??
                                '';
                            setState(() {
                              _stringEncoded = tmp;
                              myController.clear();
                            });
                          }
                        } else {
                          tmp = await _simpleRsa3Plugin.decryptString(
                                  _stringEncoded, PRIVATE_KEY) ??
                              '';
                          setState(() {
                            _stringEncoded = "";
                            myController.text = tmp;
                          });
                        }
                      } catch (e) {
                        print(e);
                      }
                    },
                    child: _stringEncoded.isEmpty
                        ? const Text("加密")
                        : const Text("解密"),
                  ),
                  ElevatedButton(
                      child: const Text("解密"),
                      onPressed: () async {
                        String tmp = "";
                        if (_stringEncoded.isNotEmpty) {
                          try {
                            tmp = await _simpleRsa3Plugin.decryptString(
                                    _stringEncoded, PRIVATE_KEY) ??
                                '';
                            setState(() {
                              _stringEncoded = "";
                              myController.text = tmp;
                            });
                          } catch (e) {
                            print(e);
                          }
                        }
                      }),
                  ElevatedButton(
                    child: const Text("重置"),
                    onPressed: () {
                      setState(() {
                        _stringEncoded = "";
                        myController.clear();
                      });
                    },
                  ),
                ],
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Card(
                  color: Colors.orangeAccent,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: <Widget>[
                        const Text("加密后的字符串"),
                        const Divider(),
                        Text(_stringEncoded),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用simple_rsa3插件进行RSA加密和解密的代码示例。这个插件允许你进行RSA公钥和私钥的生成、加密和解密操作。

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

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

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用simple_rsa3插件:

  1. 导入包
import 'package:simple_rsa3/simple_rsa3.dart';
  1. 生成RSA密钥对
Future<void> generateKeyPair() async {
  final rsaKeyPair = await SimpleRSA.generateKeyPair(2048); // 生成2048位的RSA密钥对
  final privateKey = rsaKeyPair.privateKey;
  final publicKey = rsaKeyPair.publicKey;

  print('Private Key: $privateKey');
  print('Public Key: $publicKey');
}
  1. 使用公钥加密
Future<String> encryptData(String publicKey, String plainText) async {
  final encryptedData = await SimpleRSA.encrypt(plainText, publicKey: publicKey);
  return encryptedData;
}
  1. 使用私钥解密
Future<String> decryptData(String privateKey, String encryptedData) async {
  final decryptedData = await SimpleRSA.decrypt(encryptedData, privateKey: privateKey);
  return decryptedData;
}
  1. 完整示例

下面是一个完整的示例,展示了如何生成密钥对、加密数据并解密数据:

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

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

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

class _MyAppState extends State<MyApp> {
  String? privateKey;
  String? publicKey;
  String? plainText = "Hello, RSA!";
  String? encryptedText;
  String? decryptedText;

  @override
  void initState() {
    super.initState();
    _generateKeyPair();
  }

  Future<void> _generateKeyPair() async {
    final rsaKeyPair = await SimpleRSA.generateKeyPair(2048);
    setState(() {
      privateKey = rsaKeyPair.privateKey;
      publicKey = rsaKeyPair.publicKey;
    });

    // 加密数据
    _encryptData();
  }

  Future<void> _encryptData() async {
    if (publicKey != null && plainText != null) {
      final encrypted = await encryptData(publicKey!, plainText!);
      setState(() {
        encryptedText = encrypted;

        // 解密数据
        _decryptData();
      });
    }
  }

  Future<void> _decryptData() async {
    if (privateKey != null && encryptedText != null) {
      final decrypted = await decryptData(privateKey!, encryptedText!);
      setState(() {
        decryptedText = decrypted;
      });
    }
  }

  Future<String> encryptData(String publicKey, String plainText) async {
    return await SimpleRSA.encrypt(plainText, publicKey: publicKey);
  }

  Future<String> decryptData(String privateKey, String encryptedData) async {
    return await SimpleRSA.decrypt(encryptedData, privateKey: privateKey);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('RSA Encryption/Decryption Demo'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Private Key:'),
              if (privateKey != null) Text(privateKey!),
              SizedBox(height: 16),
              Text('Public Key:'),
              if (publicKey != null) Text(publicKey!),
              SizedBox(height: 16),
              Text('Plain Text:'),
              Text(plainText ?? ''),
              SizedBox(height: 16),
              Text('Encrypted Text:'),
              if (encryptedText != null) Text(encryptedText!),
              SizedBox(height: 16),
              Text('Decrypted Text:'),
              if (decryptedText != null) Text(decryptedText!),
            ],
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中生成RSA密钥对、使用公钥加密数据以及使用私钥解密数据。请确保在实际应用中安全地存储和管理你的密钥。

回到顶部