Skip to content

Instantly share code, notes, and snippets.

@hareeqi
Created October 10, 2022 09:45
Show Gist options
  • Save hareeqi/cad307ce124ebc6a02a9afeb47340385 to your computer and use it in GitHub Desktop.
Save hareeqi/cad307ce124ebc6a02a9afeb47340385 to your computer and use it in GitHub Desktop.
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