前端加密与解密

Lirioing2025/11/06JavaScriptFEJavaScript

在前端进行的加解密只是过家家,防君子不防小人

前言

在公司中台系统中,对于一些数据内容需要存储在浏览器中,但是直接明文存入觉得不太合适,于是有了这个一般的加解密功能,小小障眼法。

简介

加密模式:AES-128-CBC

import CryptoJS from 'crypto-js';

/**
 * 生成密钥
 * @param {number} length - 字符串长度,默认16
 * @returns {string} 随机字符串
 */
export function generateRandomKey(length = 16) {
  // 可选的字符集(包含大小写字母和数字)
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let key = '';
  // 确保length是有效数字
  const len = Number(length) || 16;
  for (let i = 0; i < len; i++) {
    key += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  return key;
}
/**
 * 对message进行加密
 */
export const encryptWithStr = (message, aesKey) => {
  return CryptoJS.AES.encrypt(message, aesKey).toString();
}
/**
 * 对message进行解密
 */
export const decryptWithStr = (message, aesKey) => {
  const bytes = CryptoJS.AES.decrypt(message, aesKey);
  return bytes.toString(CryptoJS.enc.Utf8);
}



// 使用示例
const message = "需要加密的秘密信息";
const aesKey = generateRandomKey(); // 生成16位密钥

console.log("生成的密钥:", aesKey);
console.log("密钥长度:", aesKey.length);

const encrypted = encryptWithStr(message, aesKey);
console.log("加密结果:", encrypted);

const decrypted = decryptWithStr(encrypted, aesKey);
console.log("解密结果:", decrypted);

一些提醒

  1. 密钥保存:生成的密钥需要安全保存,密钥丢失则无法解密
  2. 密钥共享:如果需要多个地方解密,需要安全地共享这个密钥
上次更新 2025/12/6 16:52:48