crypto-js 加密、解密 封装cv即用

1. 安装crypto-js

yarn add crypto-js
npm install crypto-js

2. 封装加密方法

const CryptoJS = require("crypto-js");
// 设置密钥和密钥偏移量
const SECRET_KEY = CryptoJS.enc.Utf8.parse("1234123412341234");
const SECRET_IV = CryptoJS.enc.Utf8.parse("1234123412341234");

// 或者自定义密码
// const pwd = '9ea414bd183d5a11'

/**
 * 加密
 * @param {String} data 
 * @returns 
 */
export function encrypt(data) {
  if (typeof data === "object") {
    try {
      data = JSON.stringify(data);
    } catch (error) {
      console.log("encrypt error:", error);
    }
  }
  const ciphertext = CryptoJS.AES.encrypt(data, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString();

  return ciphertext;
}
/**
 * 解密
 * @param {String} ciphertext 
 * @returns 
 */
export function decrypt(ciphertext) {
  const result = CryptoJS.AES.decrypt({ciphertext:CryptoJS.enc.Base64.parse(ciphertext)}, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString(CryptoJS.enc.Utf8);

  return result;
}

3. 使用

<script>
import { encrypt, decrypt } from '@/utils/encryption'
export default {
    methods: {
        getData() {
            let obj = {
                name: '张三',
                age: '66'
            }
            //加密
            const data = encrypt(obj)
            // 解密
            const decryptData = decrypt(data)
        }
    }
}
</script>

你可能感兴趣的:(javascript,前端,开发语言,vue)