说明:本文示例使用Vue2.0框架
在这里插入图片描述

1、安装crypto-js

npm install --save crypto-js  

2、引入crypto-js

import CryptoJS from 'crypto-js'

3、在utils文件夹中新建aes.js文件,添加代码

import CryptoJS from 'crypto-js';

let AES = {
  // 加密
  encrypt: function (key, iv, data) {
    if (typeof data === 'object') {
      // 如果传入的data是json对象,先转义为json字符串
      try {
        data = JSON.stringify(data);
      } catch (error) {
        console.log('error:', error);
      }
    }
    // 统一将传入的字符串转成UTF8编码
    const dataHex = CryptoJS.enc.Utf8.parse(data); // 需要加密的数据
    const keyHex = CryptoJS.enc.Utf8.parse(key); // 秘钥
    const ivHex = CryptoJS.enc.Utf8.parse(iv); // 偏移量
    const encrypted = CryptoJS.AES.encrypt(dataHex, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC, // 加密模式
      padding: CryptoJS.pad.Pkcs7,
    });
    let encryptedVal = encrypted.ciphertext.toString();
    return encryptedVal; //  返回加密后的值
  },
  // 解密
  decrypt: function (key, iv, encryptedVal) {
    // 传入的key和iv需要和加密时候传入的key一致
    // 统一将传入的字符串转成UTF8编码
    let encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedVal);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    const keyHex = CryptoJS.enc.Utf8.parse(key); // 秘钥
    const ivHex = CryptoJS.enc.Utf8.parse(iv); // 偏移量
    let decrypt = CryptoJS.AES.decrypt(srcs, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  },
};

export default AES;

4、在App.vue中写入示例代码

<template>
  <div id="app">
    <img alt="Vue logo" src="https://vuejs.org/images/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import AES from './utils/aes.js';

export default {
  name: 'App',
  components: {
    HelloWorld,
  },
  mounted() {
    this.init();
  },
  methods: {
    init: function () {
      const key = '1234123412ABCDEF'; //十六位十六进制数作为密钥
      const iv = 'ABCDEF1234123412'; //十六位十六进制数作为密钥偏移量
      let enText = AES.encrypt(key, iv, '111');
      console.log(enText); // 84414383ba099a9def68f20677d2199b
      let deText = AES.decrypt(key, iv, enText);
      console.log(deText); // 111
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Logo

前往低代码交流专区

更多推荐