Flutter加密插件 2022-06-05 周日

2022-06-05  本文已影响0人  松哥888

现实需求

登录的时候需要输入用户名和密码。密码不能直接传给后台,应该先进行加密。
常用的加密方式有对称加密:比如AES;不对称加密:比如RSA
这里选用的是RSA不对称加密方式

插件

一般情况,这种加解密用第三方插件比较多,很少自己写。

encrypt: ^5.0.1
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/asymmetric/api.dart';

class EncryptUtil {
  ///  加密
  static String encryption(String content, String publicKeyString) {
    final parser = RSAKeyParser();
    RSAPublicKey publicKey = parser.parse(publicKeyString) as RSAPublicKey;
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    return encrypter.encrypt(content).base64;
  }

}

公钥

pubKeyString = '''
-----BEGIN PUBLIC KEY-----
$pubKeyFromBackground
-----END PUBLIC KEY-----
''';

关于接口

一般来说,加解密,只要一个字符串变换的函数就可以了,但是这个插件却引入很多自定义的类,所以需要转变一下思路。

这几个是用来处理RSA加解密中的秘钥的。读取.pem文件,或者从后台拿,扥到的公钥一般是字符串的格式。RSAKeyParser的作用就是将字符串格式的公钥转变为RSAPublicKey结构。

RSA(
      {RSAPublicKey? publicKey,
      RSAPrivateKey? privateKey,
      RSAEncoding encoding = RSAEncoding.PKCS1})

一个字符串到字符串之间变换,中间经过了这么多自定义的类,所以需要花点时间消化一下。

参考文章

encrypt: ^5.0.1;
Flutter RSA加密解密的示例代码

其他插件

mz_rsa_plugin: ^0.0.4

    //Encrypt string by public key,the public key is String (使用公钥加密字符串,公钥是字符串)
    var str1 = await MzRsaPlugin.encryptStringByPublicKey(originText, PUBLICK_KEY);
    // Decrypt the encrypted string by private key, the private key is String(使用私钥解密公钥加密过的字符串,私钥是字符串)
    var str2 = await MzRsaPlugin.decryptStringByPrivateKey(str1, PRIVART_KEY);
上一篇 下一篇

猜你喜欢

热点阅读