vue中使用AES加密

2024-10-07  本文已影响0人  我是七月

安装crypto-js

yarn add crypto-js

在utils下新建aes.js文件

import CryptoJS from 'crypto-js';
const keyStr = '12345678abcdefgh';

// 加密
export const encryptData = (word) => {
  const key = CryptoJS.enc.Utf8.parse(keyStr);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted;
};

// 解密
export function decryptData(word) {
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

// 加密-Hex
export function encryptHex(word) {
  const encrypted = encryptData(word);
  return encrypted.ciphertext.toString();
}

// 加密-Base64
export function encryptBase64(word) {
  const encrypted = encryptData(word);
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

// 解密-Hex
export function decryptHex(hexWord) {
  const wordArray = CryptoJS.enc.Hex.parse(hexWord);
  const base64Word = CryptoJS.enc.Base64.stringify(wordArray);
  return decryptData(base64Word, keyStr);
}

上一篇 下一篇

猜你喜欢

热点阅读