使用 Web Crypto API 对持久化状态进行 AES 加密。

解读

在国内一线/二线前端面试中,Redux 持久化(redux-persist)几乎是“标配”话题。面试官抛出“用 Web Crypto API 对持久化状态做 AES 加密”并不是让你背 API,而是考察三点:

  1. 你是否理解**“持久化 ≠ 安全”**——localStorage 明文存放敏感数据(token、手机号、订单金额)直接违反《个人信息保护法》与等保 2.0;
  2. 你是否能把**“Redux 数据流”与“前端密码学”无缝衔接:在数据出 Store、进磁盘之前完成可逆加密**,在重新 hydrate 时可解密且不破坏时间旅行调试;
  3. 你是否具备工程落地能力:密钥管理、IV 随机性、异步 Web Crypto 与 redux-persist 的 transform 链如何协同、性能与错误兜底。

一句话:把 redux-persist 的“serialize → 存盘”这一步替换成“AES-GCM 加密后再落盘”,并在启动时“AES-GCM 解密后再反序列化”,同时保证密钥不硬编码、不丢 IV、可轮换。

知识点

  1. Web Crypto 只能工作在 Secure Context(https 或 localhost),面试时要主动说明;
  2. AES-GCM 是浏览器唯一同时提供机密性与完整性校验的算法,比 CBC + HMAC 更简洁;
  3. CryptoKey 对象不可 JSON 化,必须 export 成 JWK 后走浏览器安全存储(IndexedDB 或 sessionStorage);
  4. redux-persist transform 是同步函数,而 Web Crypto 全是 Promise,需要异步初始化;
  5. IV 必须每次随机,并与密文拼接后一起落盘(常见做法:length(IV)=12 字节,直接 prepend);
  6. 密钥派生:国内场景优先用PBKDF2(兼容老浏览器),迭代次数≥100 000;若目标 Chrome≥110,可改用Argon2id(需第三方库);
  7. 错误隔离:解密失败返回 undefined,让 redux-persist 走 defaultState,防止整站白屏;
  8. 合规:加密字段需分级——非敏感字段可明文,敏感字段走字段级加密(子树 transform),减少加解密开销;
  9. 性能:单次状态快照 <200 KB 时,加密耗时 <16 ms(M1 Mac Chrome 103),可接受;大列表建议分页或走 IndexedDB 存储插件;
  10. 调试:开发环境可注入 __REDUX_DEVTOOLS_EXTENSION__ 的 actionSanitizer/stateSanitizer,把加密后的 payload 打码,避免泄露。

答案

以下给出一个可直接落地的 redux-persist transform 示例,采用 AES-GCM + PBKDF2,兼容 Chrome 70+,密钥由用户登录密码派生,开发环境走 localhost 自动满足 Secure Context。

// cryptoTransform.js
import { createTransform } from 'redux-persist';

const SALT = window.crypto.getRandomValues(new Uint8Array(16)); // 存 IndexedDB
let cachedKey = null; // 内存缓存,避免重复派生

async function getKey(password) {
  if (cachedKey) return cachedKey;
  const enc = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    'raw',
    enc.encode(password),
    'PBKDF2',
    false,
    ['deriveKey']
  );
  cachedKey = await crypto.subtle.deriveKey(
    { name: 'PBKDF2', salt: SALT, iterations: 150000, hash: 'SHA-256' },
    keyMaterial,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt']
  );
  return cachedKey;
}

export const cryptoTransform = password =>
  createTransform(
    // 序列化后加密
    async (inboundState, key) => {
      const iv = crypto.getRandomValues(new Uint8Array(12));
      const stateStr = JSON.stringify(inboundState);
      const encoded = new TextEncoder().encode(stateStr);
      const keyObj = await getKey(password);
      const cipherBuffer = await crypto.subtle.encrypt(
        { name: 'AES-GCM', iv },
        keyObj,
        encoded
      );
      const cipherArr = new Uint8Array(cipherBuffer);
      // IV + 密文 拼接
      const total = new Uint8Array(iv.length + cipherArr.length);
      total.set(iv, 0);
      total.set(cipherArr, iv.length);
      return btoa(String.fromCharCode(...total)); // base64 落盘
    },
    // 解密后反序列化
    async (outboundState, key) => {
      if (!outboundState) return undefined;
      try {
        const combined = Uint8Array.from(atob(outboundState), c => c.charCodeAt(0));
        const iv = combined.slice(0, 12);
        const cipher = combined.slice(12);
        const keyObj = await getKey(password);
        const plainBuffer = await crypto.subtle.decrypt(
          { name: 'AES-GCM', iv },
          keyObj,
          cipher
        );
        const decoded = new TextDecoder().decode(plainBuffer);
        return JSON.parse(decoded);
      } catch (e) {
        console.warn('[cryptoTransform] 解密失败,回退到初始状态', e);
        return undefined;
      }
    },
    // 白名单,只加密敏感子树
    { whitelist: ['user', 'order'] }
  );

使用方式:

// store.js
import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // localStorage
import rootReducer from './rootReducer';
import { cryptoTransform } from './cryptoTransform';

const persistConfig = {
  key: 'root',
  storage,
  transforms: [cryptoTransform('用户输入的登录密码')], // 生产环境走密码输入框
};

const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({ serializableCheck: false }), // Web Crypto 不可序列化
});
export const persistor = persistStore(store);

关键点回顾:

  • 密钥不落硬盘,只留在内存与 IndexedDB 的 CryptoKey 对象;
  • IV 随机 + 密文拼接,解密时正确切片;
  • transform 返回 Promise,redux-persist v6 已支持异步 transform;
  • 错误兜底返回 undefined,让 persist 自动回滚到初始 state;
  • 白名单机制,只加密含个人信息的子树,减少性能损耗;
  • Secure Context 检测:上线前必须 https,否则 crypto.subtle 为 undefined。

拓展思考

  1. 密钥轮换:用户修改密码时,需双写策略——先新旧密钥共存,等一次成功的加密快照后再删除旧密钥,防止刷新丢数据;
  2. 多端同步:若使用 WebView 内嵌在微信小程序或鸿蒙快应用,需把密钥通过JSSDK 桥接存到原生 Keychain/Keystore,避免浏览器缓存被清除;
  3. 国密合规:政府、金融项目要求SM4-GCM 替代 AES,目前只有商用密码库(如江南科友、卫士通)提供 WebAssembly 版本,需额外申请型号证书;
  4. 性能监控:可接入Sentry 自定义指标,统计加密/解密耗时,超过 50 ms 则上报,防止低端机卡顿;
  5. 服务端协同:若状态含二次验证密钥(TOTP seed),建议服务端同步加密版本号,防止本地回滚攻击;
  6. e2e 测试:Cypress 默认走 chromeWebSecurity=false 会降级为 http,需手动启动 cypress run --browser chrome --config baseUrl=https://localhost 才能访问 crypto.subtle;
  7. 未来趋势:Origin Private File System + Web Locks API 可替代 localStorage,实现大文件分块加密 + 多 tab 互斥写,2024 年已进 W3C CR,可提前预研。

掌握以上细节,你在面试中不仅能给出“能跑”的代码,还能把合规、性能、可维护性、国产化全部聊到,直接对标阿里 P7+/字节 2-2 水平。