encryptAES static method
AES-256-GCM加密 - 用于SharedPreferences 提供认证加密,防止数据篡改
Implementation
static String encryptAES({
required String plainText,
required String userKey,
}) {
// 确保密钥长度正确(32字节用于AES-256)
final keyBytes = _ensureKeyLength(userKey);
final key = Key.fromBase64(keyBytes);
// 生成随机IV(初始化向量)
final iv = IV.fromSecureRandom(16);
// 使用AES-GCM模式进行加密
final encrypter = Encrypter(AES(key, mode: AESMode.gcm));
final encrypted = encrypter.encrypt(plainText, iv: iv);
// 返回格式:IV:密文
return '${iv.base64}:${encrypted.base64}';
}