Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





Data Encryption and Decryption in Node.js using Crypto modules

The 'crypto' library is used for data eccription and decription. crypto library is used for secure data. it encrypt the data into another format. and decript the data in original format.

NodeJS provides crypto module to encrypt and decrypt data in NodeJS.

Ninitialize Node Js

To begin, execute this command.

File Name :

npm init -y

Install crypto

File Name :

npm install crypto –save

How to encrypt data in Node.js

First import the crypto module in your project

File Name :

const crypto = require ("crypto");
const algorithm = 'aes-256-cbc'; //Using AES encryption
const Securitykey = crypto.randomBytes(32);
// secret key generate 32 bytes of random data
const initVector = crypto.randomBytes(16);
// generate 16 bytes of random data
const message = "This is a secret message";
// protected data

cipher

The cipher function is used to encrypt the data.

File Name :

// the cipher function const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);

To encrypt the message, use the update() method on the cipher. Pass the first argument as the message, the second argument as utf-8 (input encoding), and hex (output encoding) as the third argument.

File Name :

let encryptedData = cipher.update(message, "utf-8", "hex");

final()

Stop the encryption using the final() method. When the final() method is called, the cipher can’t be used once more to encrypt data.

File Name :

encryptedData += cipher.final("hex");
console.log("Encrypted message: " + encryptedData);

Example :- Encription

File Name :

const crypto = require('crypto'); const algorithm = 'aes-256-cbc'; //Using AES encryption
const Securitykey = crypto.randomBytes(32);
const initVector = crypto.randomBytes(16);

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


// call encrypt function
var encdata = encrypt("mahtab_sana")
console.log(encdata )
console.log(decrypt(encdata ))

Example :- Decription

File Name :

const crypto = require('crypto'); const algorithm = 'aes-256-cbc'; //Using AES encryption
const Securitykey = crypto.randomBytes(32);
const initVector = crypto.randomBytes(16);

function decrypt(text) {
let iv = Buffer.from(text.initVector, '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();
}

Example :-

File Name :

// crypto module
const crypto = require("crypto");

const algorithm = "aes-256-cbc";

// generate 16 bytes of random data
const initVector = crypto.randomBytes(16);

// protected data
const message = "This is a secret message";

// secret key generate 32 bytes of random data
const Securitykey = crypto.randomBytes(32);

// the cipher function
const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);

// encrypt the message
// input encoding
// output encoding
let encryptedData = cipher.update(message, "utf-8", "hex");

encryptedData += cipher.final("hex");

console.log("Encrypted message: " + encryptedData);

// the decipher function
const decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);

let decryptedData = decipher.update(encryptedData, "hex", "utf-8");

decryptedData += decipher.final("utf8");

console.log("Decrypted message: " + decryptedData);

File Name :


Base64 Encoding and Decoding in Node.JS

Base64 encoding and decoding can be done in Node.js using the Buffer module. This module is loaded by default, hence no import is required.

The Buffer class can be used to manipulate streams of binary data in Node. The Buffer.from() method can create a buffer (binary data) from a given string in a specified encoding. toString() method can then be used on this buffer object to decode it as required.

File Name :


Encoding to Base64 in Node.js

To convert a string to base64, first create a buffer from the given string. then buffer can then be decoded as base64.

File Name :

let str = "sana_mahtab";
// create buffer from string
let binaryData = Buffer.from(str, "utf8");
// decode buffer as base64
let enc_data = binaryData.toString("base64");
console.log(enc_data);

Decoding Base64 in Node.js

To decode a base64 string, we need to create a buffer from the given base64 string. This buffer can then be decoded into a UTF8 string.

File Name :

// base64 encoded input string
let str = "VXNlZnVsQW5nbGU=";

// create buffer from base64 string
let binaryData = Buffer.from(str, "base64");

// decode buffer as utf8
let dec_data = binaryData.toString("utf8");
console.log(dec_data);

Generate a Secure Random Number Between min and max.

crypto module is used for generating random number.

Crypto module is also used to performs data encryption and decryption. This module is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.

random_no is a secure random integer between 0 and 999999.

const crypto = require("crypto");
// Synchronous
const random_no = crypto.randomInt(0, 1000000);
console.log(random_no);


// Asynchronous
crypto.randomInt(0, 1000000, (err, random_no) => {
if (err) throw err;
console.log(random_no);
});

const verificationCode = random_no.toString().padStart(6, "0");
// 6-digit verification code





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here