Skip to content

Instantly share code, notes, and snippets.

@yann-yinn
Created December 10, 2020 15:27
Show Gist options
  • Save yann-yinn/3f96981a0e6935b31f327a18f17ee3b9 to your computer and use it in GitHub Desktop.
Save yann-yinn/3f96981a0e6935b31f327a18f17ee3b9 to your computer and use it in GitHub Desktop.
const crypto = require("crypto");
const algorithm = "aes-256-cbc";
const secretKey = "SECRET_KEY_32_CHARS";
module.exports = {
encrypt,
decrypt,
};
// https://attacomsian.com/blog/nodejs-encrypt-decrypt-data
function encrypt(text) {
// regenerate vector each time
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: iv.toString("hex"),
content: encrypted.toString("hex"),
};
}
function decrypt(hash) {
const decipher = crypto.createDecipheriv(
algorithm,
secretKey,
Buffer.from(hash.iv, "hex")
);
const decrpyted = Buffer.concat([
decipher.update(Buffer.from(hash.content, "hex")),
decipher.final(),
]);
return decrpyted.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment