Learn to Encrypt and Decrypt Data in Node.js

in #nodejs6 years ago

I'm going to go through some examples of how you can do these operations in your project.
You can find multiple crypto algorithms to use here https://nodejs.org/api/crypto.html
My personal favorite is AES (Advanced encryption System) algorithm.

Create a new node.js project
Create a directory anywhere in your system and create a 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
No reason to do that if you have installed it using pre-built packages.

Let’s move ahead.

// 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))
Here is the output:

Encrypt and decrypt Nodejs

Encrypt and decrypt buffer
You can also encrypt and decrypt the buffers. Just pass the buffer in place of the string when you call the function and it should work.

Like this.

var hw = encrypt(Buffer.from("Some serious stuff","utf-8"))
console.log(hw)
console.log(decrypt(hw))
You can also pipe the streams in to the encrypt function to have secure encrypted data passing through the streams.

These samples should help you to get started with nodejs encryption.

Coin Marketplace

STEEM 0.28
TRX 0.26
JST 0.039
BTC 94401.09
ETH 3366.31
USDT 1.00
SBD 3.37