Skip to content

Instantly share code, notes, and snippets.

@dvgamerr
Created November 5, 2018 17:39
Show Gist options
  • Save dvgamerr/80f265bb125fade60bc84f133dce09fa to your computer and use it in GitHub Desktop.
Save dvgamerr/80f265bb125fade60bc84f133dce09fa to your computer and use it in GitHub Desktop.
Encrypt and Decrypt Data in Node.js

Create a new node.js project Create new directory anywhere in your system and create new project using the following command:

npm init -y

If you have installed Node.js by manual build then there is a chance that crypto library is not shipped with it. You can run this command to install crypto dependency.

npm install crypto --save

You don’t need to do that if you have installed it using pre-built packages.

Let’s move ahead.

Encrypt and decrypt data (Strings, numbers etc)

// Nodejs encryption with CTR
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
 let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
 let encrypted = cipher.update(text);
 encrypted = Buffer.concat([encrypted, cipher.final()]);
 return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}

function decrypt(text) {
 let iv = Buffer.from(text.iv, 'hex');
 let encryptedText = Buffer.from(text.encryptedData, 'hex');
 let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
 let decrypted = decipher.update(encryptedText);
 decrypted = Buffer.concat([decrypted, decipher.final()]);
 return decrypted.toString();
}

var hw = encrypt("Some serious stuff")
console.log(hw)
console.log(decrypt(hw))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment