前端日积月累之CryptoJS加密

126 阅读1分钟

一、安装

npm i crypto-js

二、封装方法

import CryptoJS from "crypto-js";

// 加密密钥(长度必须是 16 的整数倍,此处为 32 位)
const secretKey = "5405****778e38****fe5a12****b4ce";
// 偏移量
const iv = "solu********tion";

/**
 * @description 获取对应格式的原始字符串
 * @param {String} value 要获取原始字符串的数据
 * @param {String} encWay 获取的格式:默认UTF8
 */
const getOriginStr = (value, encWay = "Utf8") => {
  return CryptoJS.enc[encWay].parse(value);
};

/**
 * @description 使用加密秘钥,对 需要加密的参数 进行加密
 * @param {String} word 加密的数据
 * @param {String} key 密钥
 * @param {String} offset 偏移量
 * @param {String} encryption 加密方式:默认AES
 * @param {String} encWay 获取的格式:默认UTF8
 */
export const encrypt = (
  word,
  key = secretKey,
  offset = iv,
  mode = "CBC",
  padding = "Pkcs7",
  encryption = "AES",
  encWay = "Utf8"
) => {
  // 从utf8中提取原始字符串
  const utfWord = getOriginStr(word, encWay);
  const utfKey = getOriginStr(key, encWay);
  const utfOffset = getOriginStr(offset, encWay);

  const encrypted = CryptoJS[encryption].encrypt(utfWord, utfKey, {
    iv: utfOffset, // 偏移量
    mode: CryptoJS.mode[mode], // 加密模式
    padding: CryptoJS.pad[padding], // 加密填充
  });

  return encrypted.toString();
};

/**
 * @description 使用加密秘钥,对 需要解密的参数 进行解密
 * @param {String} word 要解密的数据
 * @param {String} key 密钥
 * @param {String} offset 偏移量
 * @param {String} encryption 加密方式:默认AES
 * @param {String} encWay 获取的格式:默认UTF8
 */
export const decrypt = (
  word,
  key = secretKey,
  offset = iv,
  mode = "CBC",
  padding = "Pkcs7",
  encryption = "AES",
  encWay = "Utf8"
) => {
  const utfKey = getOriginStr(key, encWay);
  const utfOffset = getOriginStr(offset, encWay);

  const decrypted = CryptoJS[encryption].decrypt(word, utfKey, {
    iv: utfOffset,
    mode: CryptoJS.mode[mode],
    padding: CryptoJS.pad[padding],
  });

  return decrypted.toString(CryptoJS.enc.Utf8);
};