crypto-js在uni-app中实现加密、解密

安装

cnpm i crypto-js

方法 encryption.ts
import CryptoJS from 'crypto-js'
let encPassword = 'emhpcnVpemh3eQ==';   // 数据传输的密钥

/**
 * AES 加密
 * @param {*} src  明文
 * @returns 密文
 */
export function aesEncrypt(src: string) {
  const key = CryptoJS.enc.Utf8.parse(setting.encPassword)
  // 加密
  var encrypted = CryptoJS.AES.encrypt(src, key, {
    iv: key,
    mode: CryptoJS.mode.CFB,
    padding: CryptoJS.pad.NoPadding
  })
  return encrypted.toString()
}

/**
 *  解密
 * @param {*} result 密文
 * @param {*} keyWord 密钥
 * @returns 明文
 */
export function aesDecrypt(result: any, keyWord: string) {
  const key = CryptoJS.enc.Latin1.parse(keyWord)
  var iv = key
  // 解密逻辑
  var decryptd = CryptoJS.AES.decrypt(result, key, {
    iv: iv,
    mode: CryptoJS.mode.CFB,
    padding: CryptoJS.pad.NoPadding
  })

  return decryptd.toString(CryptoJS.enc.Utf8)
}

/**
 * Base64 加密
 * @param {*} src  明文
 * @returns 密文
 */
export function base64Encrypt(src: string) {
  const encodedWord = CryptoJS.enc.Utf8.parse(src)
  return CryptoJS.enc.Base64.stringify(encodedWord)
}
使用
<script setup lang="ts">
import { aesEncrypt, aesDecrypt } from "@/utils/encryption";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const dataForm = reactive({
  phone: null,
  password: null
})

onLoad(() => {
  let info = uni.getStorageSync('info');
  if (info) {
    // 解密用户手机号、密码
    const data = JSON.parse(aesDecrypt(info, setting.encPassword));
    dataForm.phone = data.phone;
    dataForm.password = data.password;
  }
})

const login = () => {
    // 加密存用户手机号、密码
      let obj = {
        phone: dataForm.phone,
        password: dataForm.password
      }
      uni.setStorageSync('info', aesEncrypt(JSON.stringify(obj)));
}
</script>

你可能感兴趣的:(Uni-app,javascript,uni-app,前端)