项目中是服务端持有私钥,客户端持有公钥;
客户端使用公钥加密,并使用公钥解密服务端 用私钥加密的数据。
网上相关的资料实在再少,终于功夫不负有心人,被我找到了。附上代码。
先引入包 :
https://pub-web.flutter-io.cn/packages/encrypt
https://pub.dev/packages/pointycastle
encrypt: ^5.0.1
pointycastle: ^3.1.1
import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/services.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:pointycastle/asymmetric/pkcs1.dart';
import 'package:pointycastle/asymmetric/rsa.dart';
// import 'package:pointycastle/export.dart';
class EncryptUtil {
// Rsa加密最大长度(密钥长度/8-11)
static const int MAX_ENCRYPT_BLOCK = 245;
// Rsa解密最大长度(密钥长度/8)
static const int MAX_DECRYPT_BLOCK = 256;
//公钥分段加密
static Future encodeString(String content) async {
//加载公钥字符串
final publicPem = await rootBundle.loadString(这里写密钥路径);
//创建公钥对象
RSAPublicKey publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;
//创建加密器
final encrypter = Encrypter(RSA(publicKey: publicKey));
//分段加密
// 原始字符串转成字节数组
List<int> sourceBytes = utf8.encode(content);
//数据长度
int inputLength = sourceBytes.length;
// 缓存数组
List<int> cache = [];
// 分段加密 步长为MAX_ENCRYPT_BLOCK
for(int i=0;i<inputLength;i+=MAX_ENCRYPT_BLOCK){
//剩余长度
int endLen = inputLength-i;
List<int> item;
if(endLen > MAX_ENCRYPT_BLOCK){
item = sourceBytes.sublist(i,i+MAX_ENCRYPT_BLOCK);
}else {
item = sourceBytes.sublist(i,i+endLen);
}
// 加密后对象转换成数组存放到缓存
cache.addAll(encrypter.encryptBytes(item).bytes);
}
return base64Encode(cache);
}
//公钥分段解密
static Future decodeString(String content) async{
//加载公钥字符串
final publicPem = await rootBundle.loadString(这里写密钥路径);
//创建公钥对象
RSAPublicKey publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;
AsymmetricBlockCipher cipher = PKCS1Encoding(RSAEngine());
cipher.init(false, PublicKeyParameter<RSAPublicKey>(publicKey));
//分段解密
//原始数据
List<int> sourceBytes = base64Decode(content);
//数据长度
int inputLength = sourceBytes.length;
// 缓存数组
List<int> cache = [];
// 分段解密 步长为MAX_DECRYPT_BLOCK
for(var i=0;i<inputLength;i+=MAX_DECRYPT_BLOCK){
//剩余长度
int endLen =inputLength - i;
List<int> item;
if(endLen > MAX_DECRYPT_BLOCK){
item = sourceBytes.sublist(i,i+MAX_DECRYPT_BLOCK);
}else {
item = sourceBytes.sublist(i,i+endLen);
}
//解密后放到数组缓存
cache.addAll(cipher.process(Uint8List.fromList(item)));
}
return utf8.decode(cache);
}
}
参考资料:
https://stackoverflow.com/questions/61858252/flutter-how-to-decrypt-a-rsa-private-key-encrypted-string-if-we-have-rsa-publi
https://github.com/leocavalcante/encrypt/issues/180
https://www.jianshu.com/p/0194b99a4b3d