Getting Started With Node – Course

Using Crypto Module

Node provides built-in library called ‘crypto’ which you can use to perform cryptographic operations on data. You can do cryptographic operations on strings, buffer, and streams.

To begin with, install the library if it’s not pre-packaged with Node.

npm install crypto --save

You can use various algorithms like AES, ECDH, Diffie-Hellman, etc. Check out the crypto modules at the official site of Node.

For example, consider this code snippet.

// 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))

In the code shown above, we are encrypting data with random key and initialization vector. For more information, you can read our article on encryption and decryption here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.