crypto-js中AES的加解密封装

在项目中安装依赖:

npm i crypto-js

在使用的页面引入:

import CryptoJS from 'crypto-js'

crypto-js中AES的加解密简单的封装了一下:

    //加密
    const KEY = '000102030405060708090a0b0c0d0e0f' // 秘钥  这两个需要和后端统一
    const IV = '8a8c8fd8fe33743d3638737ea4a00698' // 偏移量  这两个需要和后端统一
    const encrypt = (word, keyStr, ivStr) => {
        // 如果后端想要的是json串的话
        // JSON.stringify(word) // 当然也可以都json一下 不看是否原本是对象
        // 大多数 我们还是使用的 JSON
        word = typeof word === 'object' ? JSON.stringify(word) : word;

        keyStr = keyStr ?? KEY; //判断是否存在ksy,不存在就用定义好的key
        ivStr = ivStr ?? IV;

        // 字符串类型的key用之前需要用uft8先parse一下才能用
        const key = CryptoJS.enc.Utf8.parse(keyStr);
        const iv = CryptoJS.enc.Utf8.parse(ivStr);

        const srcs = CryptoJS.enc.Utf8.parse(word);
        const encrypted = CryptoJS.AES.encrypt(srcs, key,
            {
                iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
        return encrypted.toString();
    }
    console.log(encrypt({ a: "zjq" }), '六卿1 加密')
    console.log(encrypt('zjq'), '六卿2 加密')
    
    // 解密
    const decrypt = (info, keyStr, ivStr) => {
        keyStr = keyStr ??  KEY; // 秘钥  这两个需要和后端统一
        ivStr = ivStr ?? IV; // 偏移量  这两个需要和后端统一
        // 字符串类型的key用之前需要用uft8先parse一下才能用
        const key = CryptoJS.enc.Utf8.parse(keyStr);
        const iv = CryptoJS.enc.Utf8.parse(ivStr);
        const decrypt = CryptoJS.AES.decrypt(info, key, {
            iv,//偏移量
            mode: CryptoJS.mode.CBC, //加密模式
            padding: CryptoJS.pad.Pkcs7,// 对应后端 PKCS5Padding  补码方式 
        });
        const CryptoJSDecrypt = CryptoJS.enc.Utf8.stringify(decrypt).toString();
        let returnData = null
        try {
            returnData = JSON.parse(CryptoJSDecrypt)
        } catch (err) {
            returnData = CryptoJSDecrypt
        }
        return returnData
    }
    console.log(decrypt('orYWcztZKmZO+P7UomQ5og=='), '六卿1 解密')
    console.log(decrypt('0WnM4/UsqpUGiJ79SCGTOg=='), '六卿2 解密')

可以直接用,可以加解密字符串或者对象,解密之后也是正常的格式;

在这里插入图片描述

参考:
https://www.cnblogs.com/huiguo/p/16601076.html
https://www.codenong.com/29512858/
https://blog.csdn.net/qq_34402069/article/details/126503916

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六卿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值