Created
October 10, 2022 09:45
-
-
Save hareeqi/cad307ce124ebc6a02a9afeb47340385 to your computer and use it in GitHub Desktop.
This file contains 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-gcm"; | |
const encrypt = (data, key) => { | |
const iv = crypto.randomBytes(16); | |
let cipher = crypto.createCipheriv(algorithm, key, iv); | |
let encrypted = cipher.update(JSON.stringify(data), "utf8", "hex"); | |
encrypted += cipher.final("hex"); | |
const tag = cipher.getAuthTag(); | |
return { content: encrypted, tag, iv }; | |
}; | |
const decrypt = (encrypted, key) => { | |
const iv = Buffer.from(encrypted.iv.data); | |
const tag = Buffer.from(encrypted.tag.data); | |
let decipher = crypto.createDecipheriv(algorithm, key, iv); | |
decipher.setAuthTag(tag); | |
let dec = decipher.update(encrypted.content, "hex", "utf8"); | |
dec += decipher.final("utf8"); | |
dec = JSON.parse(dec); | |
return dec; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment