You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用AES加解密API请求响应结果不匹配,求问题排查

Flutter AES加解密不匹配问题排查与修复

直接说问题核心错误:

  • 密钥和IV不统一:加密用的是NCKXXL2作为密钥和IV,解密却用NCKXXL3,AES加解密必须使用完全相同的密钥和IV才能还原数据,这是导致结果不匹配的首要原因。
  • 填充方式不一致:加密时使用库默认的PKCS7填充规则,解密却手动设置padding: null,导致解密无法正确处理加密时的填充字节,最终出现乱码。

修正后的完整代码如下:

import 'package:encrypt/encrypt.dart' as enc;
import 'dart:developer' as dev;

class AESService {
  // 统一密钥和IV,确保加解密使用同一组值
  static const String _keyAndIv = '7061737323313288';

  /// 加密方法
  String encryptIt(String text) {
    final key = enc.Key.fromUtf8(_keyAndIv);
    final iv = enc.IV.fromUtf8(_keyAndIv);

    final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.cbc));
    final encrypted = encrypter.encrypt(text, iv: iv);
    dev.log('加密后的值: ${encrypted.base64}');
    return encrypted.base64;
  }

  /// 解密方法
  String decryptIt(String val) {
    final key = enc.Key.fromUtf8(_keyAndIv);
    final iv = enc.IV.fromUtf8(_keyAndIv);

    // 移除padding: null,保持与加密一致的PKCS7填充规则
    final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.cbc));
    enc.Encrypted enBase64 = enc.Encrypted.fromBase64(val);
    final decrypted = encrypter.decrypt(enBase64, iv: iv);
    dev.log('解密后的值: $decrypted');
    return decrypted;
  }
}

测试验证代码:

final loginData = {'username': 'username', 'password': 'password'};
final str = loginData.toString();
// 执行加密
final encryptedStr = AESService().encryptIt(str);
// 执行解密
final decryptedStr = AESService().decryptIt(encryptedStr);
print(decryptedStr); // 输出结果:{username: username, password: password}

额外补充两个实际开发注意点:

  1. 生产环境中不建议将IV与密钥复用,最好每次加密生成随机IV,再将IV与加密数据一起传输(比如拼接在加密字符串头部,或通过JSON格式一同返回),提升加密安全性。
  2. 密钥长度需符合AES规范:16字节对应AES-128,24字节对应AES-192,32字节对应AES-256,当前使用的_keyAndIv是16字符,UTF-8编码后刚好16字节,符合AES-128要求,无需调整。

内容的提问来源于stack exchange,提问作者user2297679

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:00:58