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

Laravel中间件加密的响应数据如何在Flutter端正常解密?

Laravel加密响应Flutter端解密解决方案

你贴出的中间件代码存在逻辑遗漏,未获取请求处理后的响应对象,正确写法如下:

public function handle($request, Closure $next)
{
    // 先执行请求逻辑拿到响应
    $response = $next($request);
    return response()->json(encrypt($response->content()), $response->status());
}

1. APP_KEY的处理规则

是需要去掉base64:前缀,Laravel生成的APP_KEY默认是base64编码后的256位AES密钥,处理步骤:

  • 从.env中取出APP_KEY值,移除开头的base64:字符串
  • 将剩余的字符串做base64解码,得到32位长度的原始密钥字节,即可用于解密

2. IV的获取方式

你之前的思路错误,IV不是从密钥中提取,Laravel的encrypt()方法返回的加密串本身就包含IV信息:
Laravel加密后返回的是base64编码的JSON结构,解码后包含三个字段:

  • iv:本次加密所用初始向量的base64编码值
  • value:密文的base64编码值
  • mac:用于校验数据完整性的哈希值

Flutter端完整解密示例

依赖引入

在pubspec.yaml中添加依赖:

dependencies:
  encrypt: ^5.0.1
  crypto: ^3.0.3
  convert: ^3.1.1

解密代码示例

import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:crypto/crypto.dart' as crypto;

String laravelEncryptDecrypt(String encryptedStr, String appKey) {
  // 1. 处理APP_KEY
  final keyBase64 = appKey.replaceFirst('base64:', '');
  final keyBytes = base64Decode(keyBase64);
  final key = Key(keyBytes);

  // 2. 解析加密串获取IV和密文
  final decodedJson = jsonDecode(utf8.decode(base64Decode(encryptedStr)));
  final ivBytes = base64Decode(decodedJson['iv']);
  final iv = IV(ivBytes);
  final cipherTextBytes = base64Decode(decodedJson['value']);

  // 3. 可选:校验MAC防止数据篡改
  final mac = decodedJson['mac'];
  final calculatedMac = crypto.Hmac(crypto.sha256, keyBytes)
      .convert(utf8.encode(decodedJson['iv'] + decodedJson['value']))
      .toString();
  if (mac != calculatedMac) {
    throw Exception('数据校验失败,可能被篡改');
  }

  // 4. AES-CBC解密
  final encrypter = Encrypter(AES(key, mode: AESMode.cbc));
  final decrypted = encrypter.decrypt(Encrypted(cipherTextBytes), iv: iv);
  
  return decrypted;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:36:03