Node.js Crypto module

Node.js Crypto is the module that handles cryptographic functionality. Cryptographic functionality includes a set of wrappers for open SSL’s hash HMAC, cipher, decipher, sign and verify functions. Cryptography has great importance in network security. As you know crypto means something that is hidden or a secret. Cryptography is the field of science that deals with writing data in order to keep it secure. A hash is a string of fixed length. HMAC stands for Hash based Message Authentication code. It is a process of applying a hash algorithm to both data and secret key to change it into a single hash. Here is an example of Hash and HMAC.

File name: crypto_example1.js

const crypto = require('crypto');  
const secret = 'abcdefg';  
const hash = crypto.createHmac('sha256', secret)  
                   .update('Welcome to JavaTpoint')  
                   .digest('hex');  
console.log(hash);

Open your command prompt and run the following command to see the hash generated.

node crypto_example1.js

Here is an example of encryption. File: crypto_example2.js

const crypto = require('crypto');  
const cipher = crypto.createCipher('aes192', 'a password');  
var encrypted = cipher.update('Hello JavaTpoint', 'utf8', 'hex');  
encrypted += cipher.final('hex');  
console.log(encrypted);

Now open the command prompt and run the following code.

node crypto_example2.js 

Next is an example for decryption using decipher. File name: crypto_example3.js.

const crypto = require('crypto');  
const decipher = crypto.createDecipher('aes192', 'a password');  
var encrypted = '4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5';  
var decrypted = decipher.update(encrypted, 'hex', 'utf8');  
decrypted += decipher.final('utf8');  
console.log(decrypted);

Then run node crypto_example3.js  command in your Node.js command prompt.