Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't work with crypto #792

Closed
sujit-baniya opened this issue Sep 9, 2020 · 2 comments
Closed

Can't work with crypto #792

sujit-baniya opened this issue Sep 9, 2020 · 2 comments

Comments

@sujit-baniya
Copy link

I'm trying to use crypto library but facing various issues when importing crypto and building vue with vite.

Issue 1: const crypto = require('crypto') Not working

const crypto = require('crypto')

const ENCRYPTION_KEY = import.meta.VITE_REQUEST_ENCRYPT_KEY; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16

export function encrypt(text) {
    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
    let encrypted = cipher.update(text);

    encrypted = Buffer.concat([encrypted, cipher.final()]);

    return iv.toString('hex') + ':' + encrypted.toString('hex');
}

export function decrypt(text) {
    let textParts = text.split(':');
    let iv = Buffer.from(textParts.shift(), 'hex');
    let encryptedText = Buffer.from(textParts.join(':'), 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
    let decrypted = decipher.update(encryptedText);

    decrypted = Buffer.concat([decrypted, decipher.final()]);

    return decrypted.toString();
}

This piece of code generates: Uncaught ReferenceError: require is not defined

Issue 2: import crypto from 'crypto' Not working

Replacing

const crypto = require('crypto')

with

import crypto from 'crypto'

Generates following errors:
When vite.config.js

module.exports = {
    optimizeDeps:{
        allowNodeBuiltins: ['crypto'],
    }
}

Error: [vite] Failed to resolve module import "crypto/index.js". (imported by /src/js/encrypt.js)

Also due to above errors I can't make it work with crypto-js

What would be the possible solution to this issue?

@sujit-baniya
Copy link
Author

vite.config.js

import builtins from 'rollup-plugin-node-builtins';

const builtinsPlugin = builtins({crypto: true});
builtinsPlugin.name = 'builtins';

module.exports = {
    rollupInputOptions: {
        plugins: [
            builtinsPlugin
        ]
    }
}

Also don't work

@underfin
Copy link
Member

Please take a look in here #728.

@vitejs vitejs deleted a comment from 905868332 Oct 30, 2020
@github-actions github-actions bot locked and limited conversation to collaborators Jul 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants