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.