Photo by ev — https://unsplash.com/photos/gpjvRZyavZc

In this world where data is getting more and more important every day, we need to make sure we handle it carefully.

One solution for this is to encrypt the data you have. Luckily for us, NodeJS has a solution for us!

In this quick and simple write up we’re going to encrypt buffers.

The Node crypto module provides us with functionality that allows use to cipher, dechiper, sign and verify data. This is exactly what we want!

Let’s dive into it.

We first want to require the crypto module:

const crypto = require('crypto');

We also want to define some variables:

const algorithm = 'aes-256-ctr';

let key = 'MySuperSecretKey';

key = crypto.createHash('sha256').update(key).digest('base64').substr(0, 32);

The algorithm lets Node know how to handle then encryption.

The key is the one that is used to encrypt the actual data.

The key needs to be base64 encrypted so we do that here.

Now let’s get to the fun part!

Let’s write the encrypt function:

const encrypt = (buffer) => {

// Create an initialization vector

const iv = crypto.randomBytes(16); // Create a new cipher using the algorithm, key, and iv

const cipher = crypto.createCipheriv(algorithm, key, iv); // Create the new (encrypted) buffer

const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]); return result;

};

What this does is that it first creates an initialization vector, this protects against pattern recognition.

We then create a cipher to use to encrypt the file.

Finally, we create the actual resulting buffer that contains the iv and the encrypted data.

That’s it! We now have an encrypted buffer in Node.

But wait, how do we decrypt it you ask. Well, that’s easy too!

For our decrypt function this is gonna be all the magic:

const decrypt = (encrypted) => {

// Get the iv: the first 16 bytes

const iv = encrypted.slice(0, 16); // Get the rest

encrypted = encrypted.slice(16); // Create a decipher

const decipher = crypto.createDecipheriv(algorithm, key, iv); // Actually decrypt it

const result = Buffer.concat([decipher.update(encrypted), decipher.final()]); return result;

};

That wasn’t hard, was it?

So what this does is that it first get’s the generated iv back from the encrypted buffer.

Then gets the decipher to decrypt the file.

Finally it decrypts the file.

It’s really that simple to encrypt and decrypt in Node.

Thanks for reading. I hope this helped you and if it did, let me know!

Full working example: