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

如何使用Vanilla JavaScript加密LocalStorage中的数据?

原生JavaScript加密LocalStorage购物车数据方案

直接用浏览器原生的Web Crypto API就能实现,不需要引入任何第三方库,下面是具体实现步骤和代码:

核心思路

采用对称加密算法(推荐AES-GCM)对购物车数据加密后存入LocalStorage,读取时解密再使用。对称加密效率高,适合处理前端这类数据。

1. 生成加密密钥

首先生成安全的AES密钥,绝对不能存在LocalStorage里,可存在sessionStorage、内存中,或由服务端通过HTTPS下发(更安全)。

async function generateEncryptionKey() {
  // 生成AES-GCM算法的可导出密钥,用于后续复用
  const key = await window.crypto.subtle.generateKey(
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );
  // 将密钥导出为base64格式方便存储
  const exportedKey = await window.crypto.subtle.exportKey("raw", key);
  return btoa(String.fromCharCode(...new Uint8Array(exportedKey)));
}

2. 加密数据函数

将购物车JSON数据转成字符串后加密,返回加密后的base64字符串和初始化向量(IV,解密必需)。

async function encryptData(data, base64Key) {
  // 把base64密钥转回CryptoKey对象
  const keyBuffer = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
  const key = await window.crypto.subtle.importKey(
    "raw",
    keyBuffer,
    { name: "AES-GCM" },
    true,
    ["encrypt"]
  );

  // 生成12字节的随机初始化向量(AES-GCM推荐长度)
  const iv = window.crypto.getRandomValues(new Uint8Array(12));
  // 把数据转成ArrayBuffer格式
  const dataBuffer = new TextEncoder().encode(JSON.stringify(data));
  // 执行加密
  const encryptedBuffer = await window.crypto.subtle.encrypt(
    { name: "AES-GCM", iv: iv },
    key,
    dataBuffer
  );

  // 将加密数据和IV转成base64,一起存入LocalStorage
  const encryptedData = btoa(String.fromCharCode(...new Uint8Array(encryptedBuffer)));
  const ivBase64 = btoa(String.fromCharCode(...iv));
  return { encryptedData, ivBase64 };
}

3. 解密数据函数

从LocalStorage取出加密数据和IV,解密后转回JSON对象。

async function decryptData(encryptedData, ivBase64, base64Key) {
  // 还原密钥、IV和加密数据
  const keyBuffer = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
  const key = await window.crypto.subtle.importKey(
    "raw",
    keyBuffer,
    { name: "AES-GCM" },
    true,
    ["decrypt"]
  );
  const iv = Uint8Array.from(atob(ivBase64), c => c.charCodeAt(0));
  const encryptedBuffer = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));

  // 执行解密
  const decryptedBuffer = await window.crypto.subtle.decrypt(
    { name: "AES-GCM", iv: iv },
    key,
    encryptedBuffer
  );

  // 转回JSON对象
  return JSON.parse(new TextDecoder().decode(decryptedBuffer));
}

4. 实际使用示例

// 1. 生成密钥(仅首次使用时生成,后续复用)
const encryptionKey = await generateEncryptionKey();
// 把密钥存在sessionStorage(页面关闭后自动失效)
sessionStorage.setItem('cart-encryption-key', encryptionKey);

// 2. 加密购物车数据并存入LocalStorage
const cartData = { /* 你的购物车数据 */ };
const { encryptedData, ivBase64 } = await encryptData(cartData, encryptionKey);
localStorage.setItem('encrypted-cart', JSON.stringify({ encryptedData, ivBase64 }));

// 3. 读取并解密购物车数据
const storedCart = JSON.parse(localStorage.getItem('encrypted-cart'));
const decryptedCart = await decryptData(storedCart.encryptedData, storedCart.ivBase64, sessionStorage.getItem('cart-encryption-key'));
// decryptedCart即为原始购物车数据

关键注意事项

  • 密钥安全:密钥是加密核心,绝对不能泄露。若需跨会话复用,建议由服务端通过HTTPS绑定用户身份下发,不要存在本地持久化存储。
  • 兼容性:Web Crypto API支持所有现代浏览器(Chrome、Firefox、Edge、Safari 10.1+),无需兼容极老浏览器的话完全够用。
  • 数据备份:若用户清除浏览器存储或更换设备,密钥丢失则加密数据无法恢复,建议重要购物车数据同时在服务端备份。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:33