Skip to content

Instantly share code, notes, and snippets.

@wnqueiroz
Created January 24, 2023 21:23
Show Gist options
  • Save wnqueiroz/3f9cd8d9129446934dd52817559ff0ec to your computer and use it in GitHub Desktop.
Save wnqueiroz/3f9cd8d9129446934dd52817559ff0ec to your computer and use it in GitHub Desktop.
AES 256 GCM | Authenticated Encryption and Decryption
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
const aes256gcm = (key) => {
const encrypt = (str) => {
const iv = new randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
let enc1 = cipher.update(str, 'utf8');
let enc2 = cipher.final();
return Buffer.concat([enc1, enc2, iv, cipher.getAuthTag()]).toString("base64");
};
const decrypt = (enc) => {
enc = Buffer.from(enc, "base64");
const iv = enc.slice(enc.length - 28, enc.length - 16);
const tag = enc.slice(enc.length - 16);
enc = enc.slice(0, enc.length - 28);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
let str = decipher.update(enc, null, 'utf8');
str += decipher.final('utf8');
return str;
};
return {
encrypt,
decrypt,
};
};
// Must be 32 bytes.
const SECRET = '12345678901234567890123456789012';
const cipher = aes256gcm(SECRET);
const plaintext = 'Hello World!'
const encrypted = cipher.encrypt(plaintext);
const decrypted = cipher.decrypt(encrypted);
console.log({ encrypted, decrypted });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment