vite+vue3 uses aes-cross to report: TypeError: crypto.createCipheriv is not a function Version: "vue": "^3.2.23", "vite": "^2.6.4", "aes-cross": "^1.0.9",
To get crypto working in browser, follow instructions bellow ๐
yarn add stream-browserify browserify-zlib events process util buffer
vite.config.jsimport { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: 'util'
}
}
})
index.html<!-- [...] -->
<div id="root"></div>
<!-- node // crypto -->
<script>window.global = window;</script>
<script type="module">
import { Buffer } from "buffer/"; // <-- no typo here ("/")
import process from "process";
import EventEmitter from "events";
window.Buffer = Buffer;
window.process = process;
window.EventEmitter = EventEmitter;
</script>
<!-- [...] -->
App.vue, and testing functionin App.vue:
import crypto from 'crypto-browserify'
import { Buffer } from 'buffer/' // <-- no typo here ("/")
// test crypto
function crypt() {
// Node.js program to demonstrate the
// crypto.createCipheriv() method
const iv = crypto.randomBytes(16);
const key = crypto.pbkdf2Sync("foobar", "salt", 1000, 32, 'sha512');
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
var text = crypto.randomBytes(200)
var ourCipherText = Buffer.concat([cipher.update(text), cipher.final()])
console.log("ciphered text:", ourCipherText.toString('hex'))
return ourCipherText.toString('hex');
}
[...]
Result โ
The function crypto.createCipheriv is a node.js only function meaning it is not available in the browser like in a Vue app. You should look into SubtleCrypto which provides native web features for many encryption purposes like AES. As always, it should be noted that one should be very careful and methodical when using low-level crypto primitives, especially regarding encryption. This page provides more examples of AES encryption specifically.