Flutter是当下最流行的新兴APP跨平台开发架构。学习需趁早。
因为我的项目需要使用AES加解密,而flutter package中并没有支持Dart 2的AES加密库,所以写了Cipher2插件并拿出来开源给大家用。本文介绍如何使用Cipher2插件在Flutter app中实现AES加密解密。本文不讲述如何安装配置Flutter开发环境。如有需要我会写关于安装配置flutter开环环境的文章。
Cipher2插件地址:
各位如果有其他加密算法需求,请在github发issue,我会尽快跟进。PR is welcome!
创建项目
打开cmd命令行,cd命令定位到你想要创建项目的目录。然后创建flutter app项目
flutter create cipher2_test
用vscode打开项目目录
安装Cipher2插件
打开上图中pubspec.yaml文件的dependencies中,添加如下内容。然后ctrl + s保存,vscode会自动为你安装好插件。
dependencies:
flutter:
sdk: flutter
cipher2: any
Cipher2的API解释
Cipher2插件目前支持AES加密的cbc(128位 padding7)模式和gcm模式(128位)。插件提供了5个方法来实现加密解密。本插件所有字符串均使用UTF8编码。在处理第三方密文的时候,请注意字符串编码,以免不必要的麻烦。
- AES cbc 128位padding7加密
/*
Cipher2.encryptAesCbc128Padding7
参数:
plainText: 被加密字符串
key:128 bit字符串
iv: 128 bit字符串
返回:
经过base64编码的密文字符串
*/
String encryptedString = await Cipher2.encryptAesCbc128Padding7(plainText, key, iv);
- AES cbc 128位padding7解密
/*
Cipher2.decryptAesCbc128Padding7
参数:
encryptedString: base64编码的密文字符串
key:128 bit字符串
iv: 128 bit字符串
返回:
明文字符串
*/
String decryptedString = await Cipher2.decryptAesCbc128Padding7(encryptedString, key, iv);
- 生成GCM模式的nonce
String nonce = Cipher2.generateNonce()
- AES gcm 128位加密
/*
Cipher2.encryptAesGcm128
参数:
plainText: 被加密字符串
key:128 bit字符串
nonce: based4编码的92bit nonce,可以用Cipher2.generateNonce()生成
返回:
经过base64编码的密文字符串
*/
String encryptedString = await Cipher2.encryptAesGcm128(plaintext, key, nonce);
- AES gcm 128位解密
/*
Cipher2.decryptAesGcm128
参数:
encryptedString: base64编码的密文字符串
key:128 bit字符串
nonce: based4编码的92bit nonce,可以用Cipher2.generateNonce()生成
返回:
明文字符串
*/
result = await Cipher2.decryptAesGcm128(encryptedString, key, nonce);
使用Cipher2插件
官方提供了非常简单明了的测试用例,方便加密解密和异常捕获
https://github.com/shyandsy/c...
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String encryptedString;
String plainText = '我是shyandsy,never give up man';
String key = 'xxxxxxxxxxxxxxxx';
String iv = 'yyyyyyyyyyyyyyyy';
String decryptedString;
// 测试AES 128bit cbc padding 7加密
await testEncryptAesCbc128Padding7();
// 测试AES 128bit cbc padding 7解密
await testDecryptAesCbc128Padding7();
// 测试AES 128bit gcm加解密
await testEncryptAesGcm128(); // GenerateNonce();
// 加密,然后解密
try {
// 加密
encryptedString = await Cipher2.encryptAesCbc128Padding7(plainText, key, iv);
// 解密
decryptedString = await Cipher2.decryptAesCbc128Padding7(encryptedString, key, iv);
} on PlatformException catch(e) {
encryptedString = "";
decryptedString = "";
print("exception code: " + e.code);
print("exception message: " + e.message);
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_plainText = plainText;
_encryptedString = encryptedString;
_decryptedString = decryptedString;
});
}
读一遍test case就会用了。这里不再重复
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。