Skip to content

前端加密方案

安装依赖包

引入crypto-js

bash
yarn add crypto-js

node示例

js
/**
 * @see https://cryptojs.gitbook.io/docs/
 */
const CryptoJS = require('crypto-js')

var text = 'Message'
var key = 'xxxxxx'

var encrypted = CryptoJS.AES.encrypt(text, key).toString()
var decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8)

console.log('text', text)
console.log('key', key)
console.log('AES-encrypted', encrypted)
console.log('AES-decrypted', decrypted)

输出结果

bash
text Message
key xxxxxx
AES-encrypted U2FsdGVkX18mFLck5J77h97l/m1gWKBIuXEFHdTphvo=
AES-decrypted Message

html示例

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
  <title>Document</title>
  <style>
    #app {
      width: 700px;
      margin: 20px auto;
      padding: 20px;
      border: 1px solid #eee;
    }
  </style>
</head>
<body>
  <div id="app">
    <input type="text" v-model="text" />
    <p>AES加密:{{encrypt(text)}}</p>
    <p>AES解密:{{decrypt(text)}}</p>
  </div>
  <script>
    new Vue({
      el: '#app',
      data () {
        return {
          key: 'xxxxxx',
          text: 'Message',
        }
      },
      methods: {
        /**
         * AES加密
         */
        encrypt (text) {
          return CryptoJS.AES.encrypt(text, this.key).toString()
        },
        /**
         * AES解密
         */
        decrypt (text) {
          return CryptoJS.AES.decrypt(this.encrypt(text), this.key).toString(CryptoJS.enc.Utf8)
        }
      },
    })
  </script>
</body>
</html>

vue示例

为方便多处调用,实际使用中把加密解密方法写在一个文件中用于统一维护和使用

封装工具

cryptojs.ts

ts
/**
 * @see https://cryptojs.gitbook.io/docs/
 */
import CryptoJS from 'crypto-js'

// AES秘钥,与后端约定保持一致
const keyWords = 'xxxxxx'

// 加密方法,登录和修改密码使用
export const encrypt = (pwd: string) :string => CryptoJS.AES.encrypt(pwd, keyWords).toString()

// 解密方法,验证旧密码使用
export const decrypt = (pwd: string) :string => CryptoJS.AES.decrypt(pwd, keyWords).toString(CryptoJS.enc.Utf8)

代码示例

vue
<template>
  <input type="text" v-model="text" />
  <p>AES加密:{{encrypt(text)}}</p>
  <p>AES解密:{{decrypt(encrypt(text))}}</p>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { encrypt, decrypt } from './cryptojs' // 加密解密方法

const text = ref('Message')
</script>

Released under the MIT License.