如何在浏览器中使用 crypto 和 Buffer with vite?

How to use crypto and Buffer with vite in browser?

我有一个项目需要加密数据发送到后端。 加密货币是这样的:


const NULL_IV = Buffer.from([]) // new Buffer([]);
const crypto = require('crypto'),
  algorithm = 'aes-256-ecb'

const { bodyCrypt:{password} } = require('../config/index')

function aesEncrypt(string = '') {
  const cipher = crypto.createCipheriv(algorithm, password, NULL_IV)
  let encrypted = Buffer.concat([cipher.update(Buffer.from(string, 'utf8')), cipher.final()])
  return encrypted.toString('hex')
}


function aesDecrypt(string = '') {
  const decipher = crypto.createDecipheriv(algorithm, password, NULL_IV)
  let decrypted = Buffer.concat([decipher.update(Buffer.from(string, 'hex')), decipher.final()])
  return decrypted.toString()
}


module.exports = {
  aesEncrypt,
  aesDecrypt,
}

如何在浏览器中使用它?!! 我尝试使用cryptoJs加密,但是密文在变化,无法通过上面的代码解密。

const CryptoJS = require('crypto-js')
const data = '1'
const key = '123456x3bxiinky1xzc95wcgc0p9p2p7'
const cipher = CryptoJS.AES.encrypt(data, key, {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7,
  iv: '',
  keySize: 256
})
// 将加密后的数据转换成 Base64
const hexText= cipher.ciphertext.toString(CryptoJS.enc.Hex)


谢谢@Topaco。 如果只想加密对服务器的请求或解密服务器使用“aes-256-ecb”算法发送给我们的有效负载。 只需使用 CryptoJS 使其工作:

import CryptoJS from 'crypto-js'

import { crypt } from '@/config'

const { password } = crypt
const cryptKey = CryptoJS.enc.Utf8.parse(password)
const cryptoOptions = {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7,
  iv: '',
  keySize: 256
}

/**
 * encrypt
 * @param {*} string
 * @returns {string}
 */
function aesEncrypt(string = '') {
  const cipher = CryptoJS.AES.encrypt(string, cryptKey, cryptoOptions)
  return CryptoJS.enc.Hex.stringify(cipher.ciphertext)
}

/**
 * decrypt
 * @param {*} string
 * @returns {string}
 */
function aesDecrypt(string = '') {
  const decipher = CryptoJS.AES.decrypt(
    // make it params but not string that works.
    { ciphertext: CryptoJS.enc.Hex.parse(string) },
    cryptKey,
    cryptoOptions
  )
  return CryptoJS.enc.Utf8.stringify(decipher)
}

export { aesEncrypt, aesDecrypt }

不需要nodejs环境下的Buffer和crypto模块

如果您想了解如何使用本机 node cryptovite,您可以阅读此答案:

TypeError: crypto.createCipheriv is not a function