Flutter的RSA加密(支持modules和exponent)

因为RSA加解密,前端一般只会使用加密处理,所以只探讨加密方式。

一、已知道公钥的情况下.

已知道公钥的情况下,进行RSA加密很简单,网上都有文章说明。

  1. 首先pubspec.yaml中添加依赖:encrypt: ^4.0.0
  2. 然后类似这样代码:
import 'package:encrypt/encrypt.dart';    static Future<String> encrypt(String text) async {      String publicKeyString = await rootBundle.loadString('keys/public_key.pem');      RSAPublicKey publicKey = parser.parse(publicKeyString);      ///创建加密器      final encrypter = Encrypter(RSA(publicKey: publicKey));      return encrypter.encrypt(text).base64;  }

然而开发过程中存在其它情况,如下面的:

二、通过modules和exponent来生成公钥.

这种情况,encrypt这个库是不支持的,然后居然在网上找不到相关文章说明。刚好某项目用到此种方式,就去看有什么第三方库支持的,后来发现有个这样的库pointycastle,就尝试一下,居然可以!

  1. pubspec.yaml中添加依赖:pointycastle: ^1.0.2
  2. 如下代码:
import 'package:pointycastle/asymmetric/api.dart';      static getPublicKey(String modules, String exponent) {      var modulusInt = BigInt.parse(modules, radix: 16);      var exponentInt = BigInt.parse(exponent, radix: 16);      return RSAPublicKey(modulusInt, exponentInt);    }      static rsaEncrypt(String text, String modules) {      var publicKey = getPublicKey(modules, Config.exponent);      final encrypter = Encrypter(RSA(publicKey: publicKey));      final res = encrypter.encrypt(text).base64;      return res;    }