flutter如何实现AES加密
在Flutter中如何实现AES加密?需要用到哪些库或插件?能否提供一个完整的代码示例,包括密钥生成、加密和解密的步骤?另外,如何处理不同模式的AES加密(如CBC、ECB)和填充方式(如PKCS7)?安全性方面有哪些需要注意的地方?
2 回复
在Flutter中实现AES加密,可使用encrypt包。步骤如下:
-
添加依赖到
pubspec.yaml:dependencies: encrypt: ^5.0.1 -
导入包并编写加密代码:
import 'package:encrypt/encrypt.dart'; String encryptAES(String plainText, String key) { final encKey = Key.fromUtf8(key); final iv = IV.fromLength(16); final encrypter = Encrypter(AES(encKey)); return encrypter.encrypt(plainText, iv: iv).base64; }
注意:密钥长度需为16、24或32字节,对应AES-128/192/256。
更多关于flutter如何实现AES加密的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在 Flutter 中实现 AES 加密可以使用 encrypt 包,它提供了简单易用的 AES 加密功能。
安装依赖
在 pubspec.yaml 中添加:
dependencies:
encrypt: ^5.0.1
实现代码
import 'package:encrypt/encrypt.dart';
class AESEncryption {
static final key = Key.fromUtf8('your-32-character-key-here'); // 32字符密钥
static final iv = IV.fromLength(16); // 16字节IV
// 加密
static String encrypt(String plainText) {
final encrypter = Encrypter(AES(key));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
}
// 解密
static String decrypt(String encryptedText) {
final encrypter = Encrypter(AES(key));
final decrypted = encrypter.decrypt64(encryptedText, iv: iv);
return decrypted;
}
}
// 使用示例
void main() {
String originalText = "Hello, AES Encryption!";
// 加密
String encrypted = AESEncryption.encrypt(originalText);
print('加密后: $encrypted');
// 解密
String decrypted = AESEncryption.decrypt(encrypted);
print('解密后: $decrypted');
}
重要说明
- 密钥长度:AES-256 需要 32 字符密钥,AES-128 需要 16 字符密钥
- IV管理:生产环境中应使用随机 IV 并随密文存储
- 密钥安全:不要硬编码密钥,建议从安全存储获取
其他模式
如需使用其他模式(如 CBC、CFB),可修改为:
final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
这是一个基础的 AES 加密实现,可根据具体需求调整加密模式和参数。

