How to Encrypt and Decrypt with NodeJS by@alexadam
441 reads

How to Encrypt and Decrypt with NodeJS

tldt arrow
Read on Terminal Reader

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

@alexadam

Alex Adam

Creative Coder

About @alexadam
LEARN MORE ABOUT @ALEXADAM'S EXPERTISE AND PLACE ON THE INTERNET.
react to story with heart

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:

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

RELATED STORIES

L O A D I N G
. . . comments & more!
Hackernoon hq - po box 2206, edwards, colorado 81632, usa