Encrypt and Decrypt Data in Node.js

Pendem Shiva Shankar
2 min readDec 30, 2019

Node.js 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.

You can use multiple crypto algorithms. For the sake of examples, I am going to use AES (Advanced Encryption System) algorithm.

Create a new directory anywhere in your system and create a new project.

If you have installed Node.js by manual build then there is a chance that crypto library is not shipped with it. You can run this command to install a crypto dependency.

npm install crypto --save

You don’t need to do that if you have installed it using pre-built packages.

Let’s move ahead.

Create a new file index.js and use the following code:

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

Use command node index to see the output

Here is the output:

Encrypt and decrypt buffer

You can also encrypt and decrypt the buffers. Just pass the buffer in place of the string when you call the function and it should work.

Like this.

var hw = encrypt(Buffer.from(“Some serious stuff”,”utf-8"))
console.log(hw)
console.log(decrypt(hw))

You can also pipe the streams into the encrypt function to have secure encrypted data passing through the streams.

Checkout the source from github,

If you find this article is helpful, it would be greatly appreciated if you could tip Ether to the address below. Thank you!

0xe8312ec868303fc3f14DeA8C63A1013608038801

For more info reach me on my telegram id @chigovera .

--

--