类型错误:crypto.createCipheriv 不是函数

0 javascript rollup vue.js vite

vite+vue3 使用 aes-cross 报: TypeError: crypto.createCipheriv is not a function Version: "vue": "^3.2.23", "vite": "^2.6.4", "aes-cross": " ^1.0.9",

JEd*_*dot 5

crypto在浏览器中工作,请按照以下说明操作

\n
    \n
  1. 添加依赖项
  2. \n
\n

yarn add stream-browserify browserify-zlib events process util buffer

\n
    \n
  1. 配置vite.config.js
  2. \n
\n
import { defineConfig } from \'vite\'\nimport vue from \'@vitejs/plugin-vue\'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [vue()],\n  resolve: {\n    alias: {\n      process: "process/browser",\n      stream: "stream-browserify",\n      zlib: "browserify-zlib",\n      util: \'util\'\n    }\n  }\n})\n\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 添加JS到index.html
  2. \n
\n
<!-- [...] -->\n<div id="root"></div>\n\n<!-- node // crypto -->\n<script>window.global = window;</script>\n<script type="module">\n    import { Buffer } from "buffer/"; // <-- no typo here ("/")\n    import process from "process";\n    import EventEmitter from "events";\n        \n    window.Buffer = Buffer;\n    window.process = process;\n    window.EventEmitter = EventEmitter;\n</script>\n<!-- [...] -->\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  1. 添加导入App.vue和测试功能
  2. \n
\n

App.vue

\n
import crypto from \'crypto-browserify\'\nimport { Buffer } from \'buffer/\' // <-- no typo here ("/")\n\n// test crypto \nfunction crypt() {\n  // Node.js program to demonstrate the    \n  // crypto.createCipheriv() method\n  \n  const iv = crypto.randomBytes(16);\n  const key = crypto.pbkdf2Sync("foobar", "salt", 1000, 32, \'sha512\');\n  const cipher = crypto.createCipheriv(\'aes-256-gcm\', key, iv);\n  var text = crypto.randomBytes(200)\n  var ourCipherText = Buffer.concat([cipher.update(text), cipher.final()])\n  console.log("ciphered text:", ourCipherText.toString(\'hex\'))\n\n  return ourCipherText.toString(\'hex\');\n}\n\n[...]\n
Run Code Online (Sandbox Code Playgroud)\n

结果\xe2\x9c\x85

\n

加密浏览器截屏

\n

  • 神的圣洁母亲!!我什至不明白这是如何运作的,但确实如此。感谢您分享这个 (2认同)