IT之家

flutter RSA 分段加解密

2020-01-09  本文已影响0人  白河车

1.在assets下添加加密公钥和解密私钥

2.导入encrypt库

encrypt: ^4.0.0

3.创建加解密辅助类

class EncryptionUtil {
     //分块加密
     static Future<String> rsaEncryption(String data) async {
         // 原始json转成字节数组
         List<int> sourceBytes = utf8.encode(data);
         LogUtil.v("data" + data);
         final parser = RSAKeyParser();
        String key = await rootBundle.loadString('assets/key/public_key.pem');
         final publicKey = parser.parse(key);
         final encrypter = Encrypter(RSA(publicKey: publicKey));
         // 数据长度
         int inputLen = sourceBytes.length;
         // 加密最大长度
         int maxLen = 117;
         // 存放加密后的字节数组
         List<int> totalBytes = List();
         // 分段加密 步长为117
         for (var i = 0; i < inputLen; i += maxLen) {
             // 还剩多少字节长度
             int endLen = inputLen - i;
             List<int> item;
             if (endLen > maxLen) {
                 item = sourceBytes.sublist(i, i + maxLen);
             } else {
                 item = sourceBytes.sublist(i, i + endLen);
             }
             // 加密后的对象转换成字节数组再存放到容器
            totalBytes.addAll(encrypter.encryptBytes(item).bytes);
         }
     return base64.encode(totalBytes);
    }


 //私钥分块解密 128
 static Future<String> rsaPrivateDecrypt(String data) async {
     Uint8List sourceBytes = base64.decode(data);
     final parser = RSAKeyParser();
     String key = await rootBundle.loadString('assets/key/private_key.pem');   //根据存放位置更改
     final privateKey = parser.parse(key);
     final encrypter = Encrypter(RSA(privateKey: privateKey));
     // 数据长度
     int inputLen = sourceBytes.length;
      // 加密最大长度
      int maxLen = 128;
      // 存放加密后的字节数组
      List<int> totalBytes = List();
      // 分段加密 步长为128
     for (var i = 0; i < inputLen; i += maxLen) {
         // 还剩多少字节长度
         int endLen = inputLen - i;
         Uint8List item;
         if (endLen > maxLen) {
             item = sourceBytes.sublist(i, i + maxLen);
         } else {
             item = sourceBytes.sublist(i, i + endLen);
         }
        // 加密后的对象转换成字节数组再存放到容器
         totalBytes.addAll(encrypter.decryptBytes(Encrypted(item)));
     }
 return utf8.decode(totalBytes);
 }
}

注:分段加密参考 关于Flutter中RSA分段加密

上一篇下一篇

猜你喜欢

热点阅读