NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
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);