Skip to content

Instantly share code, notes, and snippets.

@vlucas
Last active May 26, 2023 13:27
Embed
What would you like to do?
Stronger Encryption and Decryption in Node.js
'use strict';
const crypto = require('crypto');
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16
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');
}
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();
}
module.exports = { decrypt, encrypt };
@chenvivian123
Copy link

The password generator that you included doesn't load anymore. You can try this one.
https://passwords-generator.org

@Vishu2108
Copy link

I am unable to run the code.....whenever I am entering the string.....it gives me an error...

@Venipa
Copy link

Venipa commented Apr 10, 2023

made this package a while ago for server side encrypted payloads to use for backend only: https://www.npmjs.com/package/encryption.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment