一个支持无密码房间(传输加密)和有密码房间(端到端加密)的实时聊天应用,前端 Vue3 + WebCrypto API,后端 Node.js + Koa + WebSocket,密码 bcrypt 哈希存储,消息 AES-256-GCM 加密,本地聊天记录 IndexedDB 加密存储。


一、项目概览

技术栈

层 技术
前端框架 Vue 3 + TypeScript + Vite 5
UI 组件库 Vant 4(移动端)
状态管理 Pinia
本地数据库 Dexie(IndexedDB 封装)
前端加密 WebCrypto API + JSEncrypt(RSA)
后端框架 Koa 2 + Koa-Router
WebSocket ws 8
数据库 MongoDB + Mongoose 8
后端加密 Node.js crypto + bcryptjs + node-rsa
HTTP 通信 Axios

两种房间模式

本项目的核心设计是两种房间模式对应两套完全不同的加密架构:

无密码房间 有密码房间
加密模式 传输加密 端到端加密(E2EE)
AES Key 来源 服务器生成,下发给客户端 客户端从密码 + salt 派生
服务器能否读取消息 ✅ 能(支持 AI 功能) ❌ 不能(密文原样存储转发)
历史记录存储 服务器存明文,加密后返回 服务器存密文,客户端解密
AI 功能 ✅ 支持 ❌ 禁止

二、加密体系架构

2.1 加密层次总览

┌─────────────────────── 前端(浏览器)─────────────────────┐
│                                                           │
│  ① RSA-2048 公钥加密密码 ──传输──► 服务器 RSA 私钥解密     │
│                                                           │
│  ② PBKDF2(密码, salt, 100000, SHA-256)                    │
│       │                                                   │
│       ▼                                                   │
│  ③ AES-256-GCM Key ──► 加密消息 / 解密消息 / 加密本地存储  │
│                                                           │
└───────────────────────────────────────────────────────────┘

┌─────────────────────── 后端(Node.js)───────────────────┐
│                                                           │
│  ④ bcrypt(密码, cost=10) ──► passwordHash 存入 MongoDB    │
│                                                           │
│  ⑤ AES-256-GCM ──► 无密码房间消息加解密(服务器持有 Key) │
│                                                           │
└───────────────────────────────────────────────────────────┘
javascript

2.2 五层加密详解

第①层:密码传输加密(RSA-2048)

问题:用户输入密码后,需要传给服务器验证。密码不能明文在网络上传输。

方案:RSA 非对称加密。

前端                              后端
 │                                 │
 │  GET /key/public                │
 │ ◄──────── RSA 公钥 ─────────────│  服务器启动时生成 RSA-2048 密钥对
 │                                 │
 │  RSA_Encrypt(密码, 公钥)        │
 │ ────────── 密文密码 ──────────► │  RSA_Decrypt(密文, 私钥) → 明文密码
 │                                 │  bcrypt.compare(明文密码, hash)
javascript

实现细节:

  • 后端使用 node-rsa 库,服务启动时生成 2048-bit RSA 密钥对
  • 前端使用 jsencrypt 库,用服务器公钥加密密码
  • 加密方案为 PKCS1 v1.5(encryptionScheme: 'pkcs1')
  • 公钥通过 GET /key/public 接口获取

前端实现:

// src/utils/crypto.js
function encryptPassword(password) {
  if (!password || !serverPublicKey) return false;
  const crypt = new JSEncrypt();
  crypt.setPublicKey(serverPublicKey);
  return crypt.encrypt(password);
}
javascript

后端实现:

// crypto.js
function initServerKeyPair() {
  const key = new NodeRSA({ b: 2048 });
  key.setOptions({ encryptionScheme: 'pkcs1' });
  serverKeyPair = {
    publicKey: key.exportKey('pkcs8-public-pem'),
    privateKey: key.exportKey('pkcs8-private-pem'),
    key: key
  };
}

function decryptWithServerPrivateKey(encryptedData) {
  return serverKeyPair.key.decrypt(encryptedData, 'utf8');
}
javascript

第②层:密码存储哈希(bcrypt)

问题:数据库泄露后,密码不能被反推。

方案:bcrypt 哈希,cost factor = 10。

bcrypt 的核心优势:

  • 自带 salt:hash 字符串中嵌入 salt,无需单独字段存储
  • 自适应 cost:cost=10 意味着 2^10=1024 次内部迭代,约 100ms/hash
  • 抗 GPU/ASIC:bcrypt 的内存访问模式使其不适合并行计算
// 后端 crypto.js
const BCRYPT_ROUNDS = 10;

function hashPassword(password) {
  if (!password) return '';
  return bcrypt.hashSync(password, BCRYPT_ROUNDS);
  // 输出格式: $2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
  //           ↑算法 ↑cost↑----22字符salt----↑----31字符hash----↑
}

function verifyPassword(password, passwordHash) {
  if (!password || !passwordHash) return false;
  return bcrypt.compareSync(password, passwordHash);
}
javascript

数据库 Schema 设计:

// ChatRoom.js
const chatRoomSchema = new mongoose.Schema({
  passwordHash: {
    type: String,
    required: false  // bcrypt 哈希后的密码(bcrypt 自带 salt)
  },
  salt: {
    type: String,
    required: false  // 仅用于前端 PBKDF2 密钥派生,与密码哈希无关
  },
  // 注意:没有 password 明文字段
});
javascript

关键设计决策:salt 字段和 passwordHash 字段服务于完全不同的目的:

字段 用途 谁使用
passwordHash 密码验证 后端 bcrypt.compare
salt E2EE 密钥派生 前端 PBKDF2

bcrypt 的 salt 嵌入在 hash 字符串中,不需要额外存储。而 salt 字段是给前端 PBKDF2 派生 AES Key 用的,两者互不干扰。

第③层:密钥派生(PBKDF2)

问题:有密码房间中,所有客户端需要从同一个密码派生出相同的 AES Key,但服务器不能知道这个 Key。

方案:PBKDF2(Password-Based Key Derivation Function 2)。

密码 + Salt ──► PBKDF2(100000次, SHA-256) ──► 256-bit AES Key
javascript

为什么选 PBKDF2 而不是 Argon2?

  • WebCrypto API 原生支持 PBKDF2,无需引入第三方库
  • 浏览器原生实现比 JS 实现的 Argon2 快几个数量级
  • 100,000 次迭代已经足够抵御暴力破解

前端实现(WebCrypto API):

// src/utils/crypto.js
const PBKDF2_ITERATIONS = 100000;

async function deriveKeyFromPassword(password, salt) {
  // 1. base64 salt → ArrayBuffer
  const saltBuffer = base64ToArrayBuffer(salt);

  // 2. 密码 → CryptoKey(PBKDF2 格式)
  const passwordKey = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(password),
    "PBKDF2",
    false,
    ["deriveBits"]
  );

  // 3. PBKDF2 派生 256-bit 密钥
  const bits = await crypto.subtle.deriveBits(
    {
      name: "PBKDF2",
      salt: saltBuffer,
      iterations: PBKDF2_ITERATIONS,
      hash: "SHA-256"
    },
    passwordKey,
    256
  );

  // 4. ArrayBuffer → 64字符 Hex 字符串
  return arrayBufferToHex(bits);
}
javascript

后端实现(Node.js crypto,用于验证一致性):

// crypto.js
function deriveKeyFromPassword(password, salt) {
  const saltBuffer = Buffer.from(salt, 'base64');
  return crypto.pbkdf2Sync(password, saltBuffer, 100000, 32, 'sha256')
    .toString('hex');
}
javascript

前后端一致性保障:

  • 密码编码:都使用 UTF-8
  • Salt 解码:都从 base64 解码为原始字节
  • 迭代次数:都是 100,000
  • 哈希算法:都是 SHA-256
  • 输出长度:都是 256 bit(32 字节)
  • 输出格式:都是 Hex 字符串

第④层:消息加解密(AES-256-GCM)

问题:消息在传输过程中不能被窃听或篡改。

方案:AES-256-GCM(Galois/Counter Mode)。

GCM 模式的优势:

  • 认证加密(AEAD):同时提供保密性和完整性
  • 16 字节 Tag:任何密文篡改都会导致解密失败
  • 并行计算:比 CBC 模式更快
  • 无需额外 HMAC:GCM 自带认证标签

密文格式:

┌──────────┬──────────────┬──────────┐
│  IV(12B) │  Ciphertext  │  Tag(16B)│
│  随机生成 │   变长密文    │  认证标签 │
└──────────┴──────────────┴──────────┘
│                                    │
└─────────── Base64 编码 ───────────┘
javascript

前端实现(WebCrypto API):

async function aesGcmEncrypt(data, keyHex) {
  const keyBytes = hexToArrayBuffer(keyHex);
  const iv = crypto.getRandomValues(new Uint8Array(12)); // 每次随机 IV

  const cryptoKey = await crypto.subtle.importKey(
    "raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt"]
  );

  const encrypted = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv, tagLength: 128 },
    cryptoKey,
    new TextEncoder().encode(data)
  );

  // 拼接: IV + 密文+tag
  const combined = new Uint8Array(iv.length + encrypted.byteLength);
  combined.set(iv, 0);
  combined.set(new Uint8Array(encrypted), iv.length);

  return arrayBufferToBase64(combined.buffer);
}
javascript

后端实现(Node.js crypto):

function aesEncrypt(data, keyHex) {
  const key = Buffer.from(keyHex, 'hex');
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);

  let encrypted = cipher.update(data, 'utf8');
  encrypted = Buffer.concat([encrypted, cipher.final()]);

  const tag = cipher.getAuthTag(); // 16 字节认证标签

  // 拼接: IV + 密文 + tag
  const combined = Buffer.concat([iv, encrypted, tag]);
  return combined.toString('base64');
}
javascript

第⑤层:本地存储加密

问题:聊天记录缓存在浏览器 IndexedDB 中,不能明文存储。

方案:同样使用 AES-256-GCM 加密后存入 IndexedDB。

// 保存时加密
const saveLocalChatHistory = async flag => {
  const aesKey = encrypt.getConnectionAesKey(connId);
  chatStore().setLocalChatHistory(
    await encrypt.encryptLocalData(chatList.value, aesKey),
    currentRoomId.value
  );
};

// 读取时解密
const getChatList2 = async data => {
  const aesKey = encrypt.getConnectionAesKey(connId);
  return await encrypt.decryptLocalData(data, aesKey);
};
javascript

使用 Dexie 库操作 IndexedDB:

// store/modules/chat.ts
const _db = new Dexie('_db');
_db.version(2).stores({
  chatHistory: 'roomId, data, updatedAt'
});
javascript

三、端到端加密(E2EE)完整流程

3.1 创建有密码房间

前端                                  后端                           MongoDB
 │                                     │                              │
 │  POST /room/create                  │                              │
 │  { roomName, password(RSA加密) }    │                              │
 │ ──────────────────────────────────► │                              │
 │                                     │  RSA私钥解密 → 明文密码      │
 │                                     │  salt = randomBytes(16)      │
 │                                     │  hash = bcrypt(密码, 10)     │
 │                                     │                              │
 │                                     │  createRoom({                │
 │                                     │    salt,                     │
 │                                     │    passwordHash: hash        │
 │                                     │  }) ──────────────────────► │
 │                                     │                              │  存入文档
 │  ◄─── { roomId, roomName } ─────── │                              │
javascript

3.2 加入有密码房间

前端                                  后端                           MongoDB
 │                                     │                              │
 │  ① POST /room/salt                 │                              │
 │ ──────────────────────────────────► │                              │
 │  ◄──── { salt } ───────────────── │  ◄── findOne({roomId}) ──── │
 │                                     │                              │
 │  ② PBKDF2(密码, salt, 100k)        │                              │
 │     → 派生 AES Key(仅存内存)      │                              │
 │                                     │                              │
 │  ③ GET /key/public                 │                              │
 │  ◄──── RSA 公钥 ───────────────── │                              │
 │                                     │                              │
 │  ④ RSA_Encrypt(密码)               │                              │
 │                                     │                              │
 │  ⑤ WS连接: /ws?roomId&hasPassword  │                              │
 │         &encryptedPassword=xxx      │                              │
 │ ──────────────────────────────────► │                              │
 │                                     │  RSA解密 → 明文密码          │
 │                                     │  bcrypt.compare(密码, hash)  │
 │                                     │  ✅ 验证通过                  │
 │  ◄─── 连接成功 ────────────────── │                              │
javascript

3.3 E2EE 消息收发

客户端A                               服务器                         客户端B
 │                                     │                              │
 │  AES-GCM Encrypt(消息, Key)         │                              │
 │  → { id: "uuid", ciphertext: "…" } │                              │
 │                                     │                              │
 │ ────── { id, ciphertext } ────────► │                              │
 │                                     │  appendMessage({id,ciphertext})
 │                                     │  → 密文存入 MongoDB           │
 │                                     │                              │
 │                                     │  forwardEncryptedMessage()   │
 │                                     │ ────── { id, ciphertext } ──►│
 │                                     │                              │
 │                                     │                  AES-GCM Decrypt(ciphertext, Key)
 │                                     │                  → 显示明文消息
javascript

关键点:服务器全程只看到 { id, ciphertext },无法解密。密文原样存入数据库,原样转发给其他客户端。

3.4 E2EE 历史记录加载

客户端                                服务器                         MongoDB
 │                                     │                              │
 │  WS发送: { msg: "getChatHistory" } │                              │
 │ ──────────────────────────────────► │                              │
 │                                     │  findRoomAndMessages(roomId) │
 │                                     │  ◄── chatList(含ciphertext)─ │
 │                                     │                              │
 │                                     │  过滤: 只返回有ciphertext的条目
 │                                     │  支持 lastId 分页             │
 │  ◄── { data: [{id, ciphertext}] } │                              │
 │                                     │                              │
 │  逐条 AES-GCM Decrypt(ciphertext)  │                              │
 │  → 还原明文消息                     │                              │
javascript

四、无密码房间的传输加密

无密码房间采用不同的架构:服务器生成 AES Key,消息对服务器透明。

客户端A                               服务器                         客户端B
 │                                     │                              │
 │  POST /key/room-aes                │                              │
 │ ◄──── { aesKey: "hex..." } ────── │  服务器生成 Key(内存持有)   │
 │                                     │                              │
 │  AES-GCM Encrypt(消息, aesKey)      │                              │
 │ ────── 密文 ──────────────────────►│                              │
 │                                     │  AES-GCM Decrypt → 明文      │
 │                                     │  appendMessage(明文) → MongoDB│
 │                                     │  AES-GCM Encrypt → 重新加密  │
 │                                     │ ────── 密文 ────────────────►│
 │                                     │                  AES-GCM Decrypt → 显示
javascript

服务器的作用:

  1. 解密客户端消息
  2. 明文存储到数据库
  3. 重新加密后广播给其他客户端
  4. 支持消息内容识别(AI 功能)

五、WebSocket 消息格式设计

5.1 E2EE 房间消息格式

E2EE 房间中,消息分为两类:加密消息和控制消息。

加密消息(客户端→服务器→客户端):

{
  "id": "a1b2c3d4-uuid",
  "ciphertext": "base64(IV[12B] + 密文 + Tag[16B])"
}

控制消息(明文 JSON,服务器需要识别):

{ "msg": "onlineUserInfo", "data": { "chat_id": "...", "nickName": "...", "avatar": "..." } }
{ "msg": "getOnlineNum" }
{ "msg": "getChatHistory", "lastId": "uuid" }
{ "msg": "sendWithdrawnMessage", "data": { "id": "uuid", ... } }
{ "msg": "clearHistory" }
{ "msg": "modifyUserInfo", "data": { ... } }

服务器判断逻辑:

// 1. 先尝试 JSON 解析
let parsedData = JSON.parse(rawData);

// 2. 有 msg 字段 → 控制消息
if (parsedData && parsedData.msg) {
  handleControlMessage(ws, roomId, parsedData);
  return;
}

// 3. 有 ciphertext + id → 加密消息
if (parsedData && parsedData.ciphertext && parsedData.id != null) {
  await ChatRoom.appendMessage(roomId, { id, ciphertext });
  forwardEncryptedMessage(roomId, rawData, ws);
  return;
}
javascript

5.2 前端消息发送统一封装

// setImgUrl:统一消息发送入口
const setImgUrl = async (img, connId) => {
  const isE2EE = encrypt.isEncryptedRoom(connId);
  const encrypted = await encrypt.encryptForConnection(img, connId);

  if (isE2EE && encrypted) {
    // E2EE 房间:包装为 { id, ciphertext }
    const messageId = (img && img.data && img.data.id) || "";
    return JSON.stringify({ id: messageId, ciphertext: encrypted });
  }
  // 无密码房间:直接发送密文
  return encrypted || JSON.stringify(img);
};
javascript

六、连接级密钥管理

6.1 设计问题

WebSocket 重连时会创建新的连接实例,旧的 AES Key 需要被正确替换,否则会出现:

  • 旧连接的密钥解不开新连接的消息
  • 切换房间时密钥未更新

6.2 连接版本号机制

let connectionId = 0; // 全局递增的连接版本号

const initWebSocket = async () => {
  connectionId++;
  const wsConnectionId = connectionId;
  encrypt.setCurrentConnection(wsConnectionId);

  // ... 密钥准备 ...

  encrypt.initConnection(wsConnectionId, { aesKey, hasPassword });

  // ... 建立 WebSocket ...

  newWs.onopen = () => {
    if (!isCurrentConnection(wsConnectionId)) {
      // 旧连接,忽略
      newWs.close();
      return;
    }
    onOpen(wsConnectionId, newWs);
  };
};
javascript

6.3 密钥存储 Map

// connectionStore: Map<connectionId, { aesKey, hasPassword, keyExchangeDone }>
const connectionStore = new Map();

function initConnection(connectionId, { aesKey, hasPassword }) {
  const store = _ensureConnection(connectionId);
  store.aesKey = aesKey || "";
  store.hasPassword = !!hasPassword;
  store.keyExchangeDone = !!aesKey;

  // LRU 淘汰:最多保留 5 个连接的密钥
  if (connectionStore.size > 5) {
    const keys = Array.from(connectionStore.keys());
    for (let i = 0; i < keys.length - 5; i++) {
      connectionStore.delete(keys[i]);
    }
  }
  return store;
}
javascript

七、安全特性与实现细节

7.1 密码存储安全

措施 说明
不存明文密码 数据库只有 passwordHash(bcrypt)
bcrypt cost=10 约 100ms/hash,暴力破解成本极高
bcrypt 自带 salt 每个 hash 嵌入独立 salt,防彩虹表
密码不存 localStorage 使用 sessionStorage,关闭标签页即清除

7.2 传输安全

措施 说明
RSA 加密传输密码 密码不会明文出现在网络请求中
AES-256-GCM 加密所有消息 每条消息独立加密
每消息随机 IV 12 字节随机 IV,防重放和模式分析
GCM 认证标签 16 字节 Tag,密文篡改会被检测

7.3 E2EE 房间安全

措施 说明
服务器不持有 AES Key Key 由客户端 PBKDF2 派生,只在客户端内存中
房间级独立 salt 相同密码不同房间 → 不同 Key
密文原样存储转发 服务器不解密、不重加密
禁止 AI 功能 服务器无法读取消息内容,AI 不可用
前端 AI 触发词拦截 E2EE 房间输入 AI 关键词直接 Toast 提示

7.4 本地存储安全

措施 说明
IndexedDB 加密存储 聊天记录用 AES-256-GCM 加密后存入 Dexie
会话级密码缓存 密码存 sessionStorage,关闭标签页即清除
连接级密钥隔离 每个连接独立密钥,切换房间自动更新

八、WebSocket 心跳与重连机制

8.1 心跳检测

// 客户端定时发送心跳
const start = timer => {
  const connId = encrypt.getCurrentConnectionId();
  if (encrypt.isEncryptedRoom(connId)) {
    ws.value.send(JSON.stringify({ msg: "heartbeat" }));
  } else {
    ws.value.send(await setImgUrl({ msg: "heartbeat" }, connId));
  }
};
javascript

8.2 断线重连

const onClose = (event, connId) => {
  if (isIdleFlag.value) return; // 主动断开,不重连

  encrypt.initConnection(connId, { aesKey: "", hasPassword: false });
  reconnect(); // 指数退避重连
};

const reconnect = () => {
  if (lockReconnect.value) return;
  if (reconnectNum.value >= 3) {
    showFailToast("重连失败,请刷新后再试");
    return;
  }
  reconnectNum.value++;
  reconnectTimeout.value = setTimeout(() => {
    initWebSocket(); // 重新走密钥准备 + 连接流程
  }, 5000 * reconnectNum.value); // 5s, 10s, 15s
};
javascript

重连时 initWebSocket 会重新获取 salt/AES Key,确保密钥是最新的。


九、数据编码转换工具

前端 WebCrypto API 使用 ArrayBuffer,而后端 Node.js crypto 使用 Buffer。两端需要统一的编码转换。

9.1 前端编码工具

// ArrayBuffer ↔ Hex
function arrayBufferToHex(buffer) {
  const bytes = new Uint8Array(buffer);
  return Array.from(bytes)
    .map(b => b.toString(16).padStart(2, "0"))
    .join("");
}

function hexToArrayBuffer(hex) {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
  }
  return bytes.buffer;
}

// ArrayBuffer ↔ Base64
function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  let binary = "";
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

function base64ToArrayBuffer(base64) {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return bytes.buffer;
}
javascript

9.2 后端编码对照

前端 后端
base64ToArrayBuffer(salt) Buffer.from(salt, 'base64')
arrayBufferToHex(bits) .toString('hex')
hexToArrayBuffer(keyHex) Buffer.from(keyHex, 'hex')
arrayBufferToBase64(combined) .toString('base64')
base64ToArrayBuffer(encrypted) Buffer.from(encrypted, 'base64')

十、API 接口设计

HTTP 接口

方法 路径 说明 是否需要密码
POST /room/create 创建房间 可选(RSA加密传输)
GET /room/check/:roomId 检查房间是否存在 否
POST /room/verify-password 验证房间密码 是(RSA加密传输)
GET /room/list 获取公共房间列表 否
POST /room/salt 获取房间 salt(E2EE密钥派生用) 否
POST /room/joined 获取已加入房间列表 否
GET /room/info/:roomId 获取房间信息 否
GET /key/public 获取服务器 RSA 公钥 否
POST /key/room-aes 获取房间 AES Key(无密码房间) 否

WebSocket 连接

ws://host/chat/ws?roomId=xxx&hasPassword=true&encryptedPassword=xxx
javascript
参数 说明
roomId 房间 ID
hasPassword 是否有密码
encryptedPassword RSA 加密后的密码(有密码房间必须)

十一、E2EE 房间控制消息处理

E2EE 房间的控制消息以明文 JSON传输,因为服务器需要识别消息类型来处理逻辑:

function handleControlMessage(ws, roomId, data) {
  if (data.msg === 'onlineUserInfo') {
    // 更新用户信息,广播在线用户列表
  } else if (data.msg === 'getOnlineNum') {
    // 返回在线人数
  } else if (data.msg === 'getChatHistory') {
    // 从数据库取密文,过滤后返回(支持 lastId 分页)
    const result = await ChatRoom.findRoomAndMessages(roomId);
    let chatList = result.success ? result.data.chatList : [];
    if (data.lastId) {
      const lastIdIndex = chatList.findIndex(item => item.id == data.lastId);
      if (lastIdIndex !== -1) chatList = chatList.slice(lastIdIndex + 1);
    }
    const ciphertextList = chatList.filter(item => item.ciphertext).map(item => ({
      id: item.id,
      ciphertext: item.ciphertext
    }));
    ws.send(JSON.stringify({ msg: 'getChatHistory_ok', data: ciphertextList }));
  } else if (data.msg === 'sendWithdrawnMessage') {
    // 通过 id 从数据库删除密文,广播撤回通知
    await ChatRoom.withdrawMessage(roomId, data.data.id);
  } else if (data.msg === 'clearHistory') {
    // 清空数据库中的聊天记录
    await ChatRoom.overwriteChatList(roomId, []);
  }
}
javascript

十二、踩坑记录

12.1 crypto-js 不支持 GCM 模式

最初使用 crypto-js 库,发现它不支持 AES-GCM 模式,只支持 CBC。CBC 模式需要手动实现 HMAC 做认证,容易出错。最终改为原生 WebCrypto API(前端)和 Node.js crypto 模块(后端),原生支持 GCM。

12.2 E2EE 房间控制消息被错误加密

最初实现时,E2EE 房间的所有消息(包括控制消息)都走加密通道,导致服务器无法识别 getChatHistory、onlineUserInfo 等控制消息。修复方案:控制消息用明文 JSON 发送,加密消息用 { id, ciphertext } 格式。

12.3 timingSafeEqual 长度不匹配

crypto.timingSafeEqual 要求两个 Buffer 长度完全相同,否则抛 RangeError。如果 passwordHash 为空字符串,Buffer.from("") 长度为 0,会导致未捕获异常。修复:添加空值检查和长度校验。

12.4 消息 id 的 falsy 判断

消息格式 { id, ciphertext } 中,id 为空字符串 "" 时是 falsy。判断条件 parsedData.id 会错误地拒绝 id="" 的消息。修复:改为 parsedData.id != null。

12.5 MongoDB Schema 默认值浪费存储

E2EE 房间消息只需要 { id, ciphertext, createdAt },但 messageSchema 中其他字段(avatar, data, nickName 等)都有默认空值,会被 Mongoose 自动写入数据库。虽然不影响功能,但浪费存储空间。

12.6 密码明文存储在 localStorage

最初将密码明文存储在 localStorage 中,XSS 攻击可以轻松读取。修复:改为 sessionStorage,关闭标签页即清除。


写于 2026 年 6 月,记录端到端加密聊天室的完整实现过程。
在线地址 https://www.yzzone.com/chat


评论
avatar
0 评论
目录