nuxtjs 中使用crypto-js进行加密以及解密

文章介绍了如何在utils.js文件中创建一个模块,该模块导入CryptoJS库并定义了用于AES加密和解密的函数。这些函数被注入到Nuxt.js应用中,可以在组件的asyncData和methods中使用,以便对字符串和对象进行加解密操作。
摘要由CSDN通过智能技术生成

在utils文件夹中新建utils.js

import CryptoJS from 'crypto-js'
const key = CryptoJS.enc.Utf8.parse("1234567890000000");
const iv = CryptoJS.enc.Utf8.parse("1234567890000000");
export default (app,inject) => {
    inject('encrypt',word=>{
        let encrypted = "";
        if (typeof word == "string") {
            encrypted = CryptoJS.AES.encrypt(word, key, { iv: iv }).toString()
        } else if (typeof word == "object") {
            const data = JSON.stringify(word);
            encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv }).toString()
        }
        return encrypted;
    })

    inject('decrypt',word=>{
        const decryptedStr = CryptoJS.AES.decrypt(word, key, { iv: iv }).toString(CryptoJS.enc.Utf8)
        return decryptedStr.toString();
    })
    
}

 在nuxt.config.js中引入

export default {

  plugins: [
    '@/utils/utils',
  ],
 
}

组件中使用:

export default{
    //在asyncData中使用
    asyncData(app){
       //加密
        const str = app.$encrypt('123455')
        //解密
        const str2 = app.$decrypt(str)
    },
    //在methods中使用的话可以直接通过this.$encrypt和this.$decrypt进行加解密
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值