Search code examples
browserbuffercryptojs

How to use crypto and Buffer with vite in browser?


I have a project need to encrypt data to send to backend. and the crypto is like this:


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,
}

How can I use this in browser?!! I try to use cryptoJs to encrypt, but the ciphertext is changing and couldnt be decrypt by the code above.

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)



Solution

  • Thanks @Topaco. If just want to encrypt request to a server or decrypt payload that a server send to us using "aes-256-ecb" algorithm. Just use CryptoJS to make it works:

    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 }
    
    

    It doesnt need Buffer or crypto module that in nodejs environment.