paint-brush
How to Encrypt and Decrypt with NodeJSby@alexadam
9,396 reads
9,396 reads

How to Encrypt and Decrypt with NodeJS

by Alex AdamAugust 21st, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How to encrypt text: create a file named encdec.js and paste: require('crypto')const encrypt = (plainText, password) Then run: encode, decrypt, encode and test: "Hello World," "secret1234" Then run the decryption function: "decrypted" and "encrypted" output: Hello World.js. Then run encode and decrypt: "Decry" and encode text: "Hey World. What do you know? How do we know?"

Company Mentioned

Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - How to Encrypt and Decrypt with NodeJS
Alex Adam HackerNoon profile picture

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);
  }
}

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

Then run:

node encdec.js

# Output:
encrypted text af9efafd353a5a7e27f31262dac12d6b:eb1dd75ea6c84e25300d5a244138ab3c

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

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

Then run :

node encdec.js

# Output
encrypted text 71596b9f5a99532f438fc5669b845680:248f6cb24a4ebeb174bbb73953115fd5
decrypted text Hello World

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


Also published on https://alexadam.dev/blog/encrypt-decrypt-in-node.html.