其他分享
首页 > 其他分享> > 前端AES加密

前端AES加密

作者:互联网

1.安装依赖

npm install crypto-js

2.引入crypto-js

 

import CryptoJS from "crypto-js";
//秘钥
const CRYPTOJSKEY = "abcdefgabcdefg12";
// 加密
export function encrypt(plaintText) {
  var plaintText = plaintText;
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  };
  var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY);
  var encryptedData = CryptoJS.AES.encrypt(plaintText, key, options);
  var encryptedBase64Str = encryptedData.toString().replace(/\//g, "_");
  encryptedBase64Str = encryptedBase64Str.replace(/\+/g, "-");
  return encryptedBase64Str;
}
//解密
export function decrypt(encryptedBase64Str) {
  var vals = encryptedBase64Str.replace(/\-/g, '+').replace(/_/g, '/');
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  };
  var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY);
  var decryptedData = CryptoJS.AES.decrypt(vals, key, options);
  var decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);
  return decryptedStr;
}

3.使用

<script>
  import { encrypt, decrypt } from '../../../utils/crypto.js';
export default {
  name: 'ApprovalManagement',
  data() {
    return {
    };
  },
  mounted() {
    this.aes();
  },
  methods: {
    aes() {
      let password = '123456';
      console.log('加密', encrypt(password));
      console.log(1);
      console.log('解密', decrypt(encrypt(password)));
    }
  }
};

 

标签:AES,加密,前端,decrypt,replace,encryptedBase64Str,var,encrypt,CryptoJS
来源: https://www.cnblogs.com/spotlighter/p/16466030.html