Flutter中dio_cache_interceptor缓存拦截器如何实现加解密?
dio_cache_interceptor cipher加密功能实现方案
dio_cache_interceptor的cipher参数接收Cipher抽象类实例,你只需要自行实现该类的加解密方法即可,以下是可直接使用的AES加密实现示例:
第一步:添加依赖
在pubspec.yaml中引入加密工具包:
dependencies: dio_cache_interceptor: ^3.4.2 encrypt: ^5.0.1 # 用于AES加解密,使用最新稳定版即可
第二步:实现自定义加密类
直接复制以下代码即可,可根据需求调整加密算法和密钥:
import 'dart:typed_data'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:encrypt/encrypt.dart'; class CustomCacheCipher implements Cipher { // 32位密钥对应AES-256,自行替换为你自己的密钥,生产环境注意保密不要硬编码 final _aesKey = Key.fromUtf8('your_32_length_secret_key_12345678'); // 16位IV向量,自行替换 final _iv = IV.fromUtf8('your_16_length_iv_'); late final _encrypter = Encrypter(AES(_aesKey, mode: AESMode.cbc)); @override Uint8List decrypt(Uint8List encrypted) { return _encrypter.decryptBytes(Encrypted(encrypted), iv: _iv); } @override Uint8List encrypt(Uint8List plain) { return _encrypter.encryptBytes(plain, iv: _iv).bytes; } }
第三步:替换CacheOptions中的cipher参数
把你原来的null替换为自定义加密类的实例即可:
// 如需保留const修饰,可将CustomCacheCipher的构造方法声明为const,对应属性也改为常量声明 final options = CacheOptions( store: MemCacheStore(), policy: CachePolicy.request, hitCacheOnErrorExcept: [401, 403], maxStale: const Duration(days: 7), priority: CachePriority.normal, cipher: CustomCacheCipher(), // 替换为自定义加密实例 keyBuilder: CacheOptions.defaultCacheKeyBuilder, allowPostMethod: false, );
注意事项
- 如果你使用的是
MemCacheStore,缓存仅存在于内存中,加密必要性较低;如果使用FileCacheStore或HiveCacheStore等持久化存储方案,加密可以有效保护本地缓存数据 - 加密算法可根据需求自行调整,只要实现
Cipher接口的两个方法即可正常被包调用
内容的提问来源于stack exchange,提问作者Junaid Tariq
相关产品推荐
相关产品推荐

