1.在assets下添加加密公鑰和解密私鑰
2.導(dǎo)入encrypt庫(kù)
encrypt: ^4.0.0
3.創(chuàng)建加解密輔助類(lèi)
class EncryptionUtil {
?????//分塊加密
?????static Future<String> rsaEncryption(String data) async {
?????????// 原始json轉(zhuǎn)成字節(jié)數(shù)組
?????????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));
?????????// 數(shù)據(jù)長(zhǎng)度
?????????int inputLen = sourceBytes.length;
?????????// 加密最大長(zhǎng)度
?????????int maxLen = 117;
?????????// 存放加密后的字節(jié)數(shù)組
?????????List<int> totalBytes = List();
?????????// 分段加密 步長(zhǎng)為117
?????????for (var i = 0; i < inputLen; i += maxLen) {
?????????????// 還剩多少字節(jié)長(zhǎng)度
?????????????int endLen = inputLen - i;
?????????????List<int> item;
?????????????if (endLen > maxLen) {
?????????????????item = sourceBytes.sublist(i, i + maxLen);
?????????????} else {
?????????????????item = sourceBytes.sublist(i, i + endLen);
?????????????}
?????????????// 加密后的對(duì)象轉(zhuǎn)換成字節(jié)數(shù)組再存放到容器
? ? ? ? ????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');? ?//根據(jù)存放位置更改
?????final privateKey = parser.parse(key);
? ? ?final encrypter = Encrypter(RSA(privateKey: privateKey));
?????// 數(shù)據(jù)長(zhǎng)度
?????int inputLen = sourceBytes.length;
? ? ? // 加密最大長(zhǎng)度
? ? ? int maxLen = 128;
? ? ? // 存放加密后的字節(jié)數(shù)組
? ? ? List<int> totalBytes = List();
? ? ? // 分段加密 步長(zhǎng)為128
?????for (var i = 0; i < inputLen; i += maxLen) {
?????????// 還剩多少字節(jié)長(zhǎng)度
?????????int endLen = inputLen - i;
?????????Uint8List item;
?????????if (endLen > maxLen) {
?????????????item = sourceBytes.sublist(i, i + maxLen);
?????????} else {
?????????????item = sourceBytes.sublist(i, i + endLen);
?????????}
? ? ? ? // 加密后的對(duì)象轉(zhuǎn)換成字節(jié)數(shù)組再存放到容器
?????????totalBytes.addAll(encrypter.decryptBytes(Encrypted(item)));
?????}
?return utf8.decode(totalBytes);
?}
}
注:分段加密參考?關(guān)于Flutter中RSA分段加密