AES数据加密|解密 ECB_Pkcs7_128

调试工具:https://the-x.cn/cryptography/Aes.aspx

  1. 先安装 crypto-js
    npm install crypto-js --save-dev
  2. 增加文件aes.js
    // 导入 crypto-js 包
    const CryptoJS = require('crypto-js')
    const keyVal = '123456' // 可以自己定义
    // 设置数据块长度
    const keySize = 128
    
    /**
     * 生成密钥字节数组, 原始密钥字符串不足128位, 补填0.
     * @param {string} key - 原始 key 值
     * @return Buffer
     */
    const fillKey = (key) => {
      const filledKey = Buffer.alloc(keySize / 8)
      const keys = Buffer.from(key)
      if (keys.length < filledKey.length) {
        filledKey.map((b, i) => filledKey[i] = keys[i])
      }
      return filledKey
    }
    
    /**
     * 定义加密函数
     * @param {string} data - 需要加密的数据, 传过来前先进行 JSON.stringify(data);
     * @param {string} key - 加密使用的 key
     */
    export function aesEncrypt(data, key) {
      key = CryptoJS.enc.Utf8.parse(fillKey(key || keyVal))
      /**
       * CipherOption, 加密的一些选项:
       *   mode: 加密模式, 可取值(CBC, CFB, CTR, CTRGladman, OFB, ECB), 都在 CryptoJS.mode 对象下
       *   padding: 填充方式, 可取值(Pkcs7, AnsiX923, Iso10126, Iso97971, ZeroPadding, NoPadding), 都在 CryptoJS.pad 对象下
       *   iv: 偏移量, mode === ECB 时, 不需要 iv
       * 返回的是一个加密对象
       */
      const cipher = CryptoJS.AES.encrypt(data, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
        iv: ''
      })
      // 将加密后的数据转换成 Base64
      const base64Cipher = cipher.ciphertext.toString(CryptoJS.enc.Base64)
      // 处理 Android 某些低版的BUG
      const resultCipher = base64Cipher.replace(/\+/g, '-').replace(/\//g, '_')
      // 返回加密后的经过处理的 Base64
      return resultCipher
    }
    
    /**
     1. 定义解密函数
     2. @param {string} encrypted - 加密的数据;
     3. @param {string} key - 加密使用的 key
     */
    export function aesDecrypt(encrypted, key) {
      key = CryptoJS.enc.Utf8.parse(fillKey(key || keyVal))
      // 先将 Base64 还原一下, 因为加密的时候做了一些字符的替换
      const restoreBase64 = encrypted.replace(/\-/g, '+').replace(/_/g, '/')
      // 这里 mode, padding, iv 一定要跟加密的时候完全一样
      // 返回的是一个解密后的对象
      const decipher = CryptoJS.AES.decrypt(restoreBase64, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
        iv: ''
      })
      // 将解密对象转换成 UTF8 的字符串
      const resultDecipher = CryptoJS.enc.Utf8.stringify(decipher)
      // 返回解密结果
      return resultDecipher
    }
    
  3. 引用使用
    import { aesEncrypt, aesDecrypt } from '@/utils/aes'
    const encrypted = aesEncrypt('11111')
    console.log('加密结果: ', encrypted)
    const aes = aesDecrypt(encrypted)
    console.log('解密密结果: ', encrypted)
    

踩了好久的🕳,记录一下!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值