Created
December 10, 2020 15:27
-
-
Save yann-yinn/3f96981a0e6935b31f327a18f17ee3b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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