背景介绍
在Flutter开发中,处于安全考虑,可能需要将请求数据加密处理后再传输,今天我们就介绍下Flutter种如何进行加解密,和如何将加解密应用到网络请求中,正文开始
引入加密库
encrypt: ^5.0.3
使用加密函数进行加密
AES加密
import 'package:encrypt/encrypt.dart' as ECP;
import 'package:encrypt/encrypt.dart';
///AES加密
String _aesEncrypted(String aesKey, String ivKey, String text) {
print("aes加密,原文:$text");
final key = ECP.Key.fromUtf8(aesKey);
final iv = ECP.IV.fromUtf8(ivKey);
final encrypter = ECP.Encrypter(ECP.AES(key, mode: ECP.AESMode.cbc, padding: "PKCS7"));
final encrypted = encrypter.encrypt(text, iv: iv);
print("aes加密${encrypted.base64}");
return encrypted.base64;
}
AES解密
///AES解密
String _aesDecrypted(String aesKey, String ivKey, String text) {
try {
final key = ECP.Key.fromUtf8(aesKey);
final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
String decrypt64 = encrypter.decrypt64(text, iv: IV.fromUtf8(ivKey));
print("aes decode :$decrypt64");
return decrypt64;
} catch (err) {
print("aes decode error:$err");
return "base64";
}
}
此时可能会好奇,加密用的key和向量从哪来,这时候你可能需要了解下AES加密的原理,因为AES是对称加密,需要和服务端约定好加密的key和向量,一般安全起见是通过服务器动态下发。
RSA加密
///使用rsa加密数据
String _rsaEncrypt(String text) {
try {
RSAAsymmetricKey publicKey = RSAKeyParser().parse(publicKeyString);
RSAPublicKey? key = publicKey as RSAPublicKey?;
//创建加密器
final encrypter = Encrypter(RSA(publicKey: key));
print("rsa加密 ${encrypter.encrypt(text).base64}");
return encrypter.encrypt(text).base64;
} catch (err) {
return err.toString();
}
}
RSA解密(RSA是非对称加密算法,解密需要私钥,这里只是模拟)
///使用rsa解密
Future<String> _rsaDecrypt(String privateKey,String text) async {
String privateKeyString = "-----BEGIN PUBLIC KEY-----\n"
"$privateKey"
"\n-----END PUBLIC KEY-----";
try {
RSAAsymmetricKey privateKey = RSAKeyParser().parse(privateKeyString);
RSAPrivateKey? key = privateKey as RSAPrivateKey?;
//创建加密器
final decrypter = Encrypter(RSA(privateKey: key));
print(decrypter.decrypt(Encrypted.from64(text)));
return decrypter.decrypt(Encrypted.fromBase64(text));
} catch (err) {
return err.toString();
}
}
Flutter的网络请求时如何使用
重头戏来了,加密一般用在数据传输,移动端APP与服务器交互中的数据安全就需要用到了,我在这里模拟一个网络请求,需要将参数和请求头进行加密
_https() async {
//思路
//1.先生成128位的key和向量
String aesKey = _creatRandomStr(128);
String ivKey = _creatRandomStr(128);
//4.请求body参数AES加密
var url = "http://www.test.com";
var params = {"token": "xxx", "id": "111"};
String jsonString = jsonEncode(params);
Dio dio = new Dio();
dio.options.contentType = "application/json";
///请求header的配置,aes_key+aes_iv组合RSA加密
dio.options.headers["AES_KEY_AND_IV"] = await _testRSA('${aesKey}$ivKey');
///发起请求,body数据转json,然后AES加密(测试数据key,iv写死)
Response response = await dio.post(url,
data: _aesEncrypted(aesKey, ivKey, jsonString));
print(response.data);
///返回数据response.data["data"],通过AES解密
String results = _aesDecrypted(aesKey, ivKey, response.data["data"]);
print(results);
}
以上就是在Flutter的网络请求中使用AES加密解密的全过程,希望能帮到同学们。