Categories
JavaScript Answers

How to encrypt data that needs to be decrypted in Node.js?

Spread the love

To encrypt data that needs to be decrypted in Node.js, we use the crypto module.

For instance, we write

const crypto = require("crypto");
const assert = require("assert");

const algorithm = "aes256";
const key = "password";
const text = "I love kittens";

const cipher = crypto.createCipher(algorithm, key);
const encrypted = cipher.update(text, "utf8", "hex") + cipher.final("hex");

const decipher = crypto.createDecipher(algorithm, key);
const decrypted =
  decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8");

to create a cipher with createCipher.

Then we call cipher.update to encrypt the text string.

Next, we call createDecipher with the same algorithm and key we call createCipher with.

The we call decipher.update to decrypt the encrypted string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *