DEV Community

Alex Adam
Alex Adam

Posted on • Originally published at alexadam.dev

1

Encrypt and Decrypt in NodeJS

How to encrypt text

Create a file named encdec.js and paste:

const crypto = require("crypto")

const encrypt = (plainText, password) => {
  try {
    const iv = crypto.randomBytes(16);
    const key = crypto.createHash('sha256').update(password).digest('base64').substr(0, 32);
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);

    let encrypted = cipher.update(plainText);
    encrypted = Buffer.concat([encrypted, cipher.final()])
    return iv.toString('hex') + ':' + encrypted.toString('hex');

  } catch (error) {
    console.log(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's test it:

Append these lines:


const encrypt = (plainText, password) => {
  ...
}

const text = "Hello World"
const pass = "secret1234"

const encText = encrypt(text, pass)
console.log('encrypted text', encText);
Enter fullscreen mode Exit fullscreen mode

Then run:

node encdec.js

# Output:
encrypted text af9efafd353a5a7e27f31262dac12d6b:eb1dd75ea6c84e25300d5a244138ab3c
Enter fullscreen mode Exit fullscreen mode

How to decrypt the encrypted text

Add the decryption function:

const decrypt = (encryptedText, password) => {
  try {
    const textParts = encryptedText.split(':');
    const iv = Buffer.from(textParts.shift(), 'hex');

    const encryptedData = Buffer.from(textParts.join(':'), 'hex');
    const key = crypto.createHash('sha256').update(password).digest('base64').substr(0, 32);
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);

    const decrypted = decipher.update(encryptedData);
    const decryptedText = Buffer.concat([decrypted, decipher.final()]);
    return decryptedText.toString();
  } catch (error) {
    console.log(error)
  }
}
Enter fullscreen mode Exit fullscreen mode

And a test:

const text = "Hello World"
const pass = "secret1234"

const encText = encrypt(text, pass)
console.log('encrypted text', encText);

const decText = decrypt(encText, pass)
console.log('decrypted text', decText);
Enter fullscreen mode Exit fullscreen mode

Then run :

node encdec.js

# Output
encrypted text 71596b9f5a99532f438fc5669b845680:248f6cb24a4ebeb174bbb73953115fd5
decrypted text Hello World
Enter fullscreen mode Exit fullscreen mode

Source: https://gist.github.com/vlucas/2bd40f62d20c1d49237a109d491974eb

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more