Encrypt and decrypt data Using AES encryption algorithm in NodeJS

Posted By : Praddumn Kumar | 10-Apr-2017

Nodejs offers great support for cryptography . One of them are AES technique. AES stands for Avanced Encryption Standard ,is a symmetric encryption algorithm. AES was designed to be efficient in both hardware and software, and supports a block length of 128 bits and key lengths of 128, 192, and 256 bits.

In Node.js the crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.

We need to use  var crypto = require('crypto') to access this module in our application.

Let's take a example of encrypting and decrypting text using aes192 technique:


const crypto = require('crypto');
// function to encrypt data ....
var encryptInformation= function(KEY,normalText){
const cipher = crypto.createCipher('aes192', KEY);
var encrypted = cipher.update(text,'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}

we can use cipher.update() and cipher.final() methods to produce the encrypted data with the plaintext.
In the above example crypto.createCipher() method is used to create Cipher instances. Cipher objects are not to be created directly using the new keyword.


const crypto = require('crypto'); 
// function to decryt data..............
var decryptInformation = function(KEY,encryptedText){ 
    const decipher = crypto.createDecipher('aes192', KEY) 
    var decrypted = decipher.update(text,'hex','utf8') 
    decrypted += decipher.final('utf8'); 
    return decrypted; 
 }

In the above example crypto.createDecipher() method is used to create Decipher instances. Decipher objects are also not to be created directly using the new keyword.

In the first method of this example we need to pass the normal text that need to encrypt and a KEY value that can be used as password . KEY value should be same in both the methods because this is used as password to encrypt and and decrypt the data.

// calling to encryption function to encrypt text......

var encryptedData = encryptInformation(KEY , “some text that need to encrypt”); 

In the second function of above example we are using KEY and encrypted data to get the actual text , that we have encrypted in first function .

// calling to decryption function to decrypt text.......

var decryptedData = decryptInformation(KEY , encryptedText);

This will give us actual data that we have encrypted in the above function.

THANKS

About Author

Author Image
Praddumn Kumar

Praddumn is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..