Skip to content

Instantly share code, notes, and snippets.

@youngkiu
Forked from rjz/crypto-aes-256-gcm-demo.js
Last active November 12, 2022 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youngkiu/750b369177425f7e06b52dc3ae92cd8e to your computer and use it in GitHub Desktop.
Save youngkiu/750b369177425f7e06b52dc3ae92cd8e to your computer and use it in GitHub Desktop.
example using node.js crypto API with aes-256-gcm
const crypto = require('crypto');
// Demo implementation of using `aes-256-gcm` with node.js's `crypto` lib.
const aes256gcm = (key) => {
const ALGO = 'aes-256-gcm';
// encrypt returns base64-encoded ciphertext
const encrypt = (str) => {
// The `iv` for a given key must be globally unique to prevent
// against forgery attacks. `randomBytes` is convenient for
// demonstration but a poor way to achieve this in practice.
//
// See: e.g. https://csrc.nist.gov/publications/detail/sp/800-38d/final
const iv = Buffer.from(crypto.randomBytes(12), 'utf8');
const cipher = crypto.createCipheriv(ALGO, key, iv);
// Hint: Larger inputs (it's GCM, after all!) should use the stream API
let enc = cipher.update(str, 'utf8', 'base64');
enc += cipher.final('base64');
return [enc, iv, cipher.getAuthTag()];
};
// decrypt decodes base64-encoded ciphertext into a utf8-encoded string
const decrypt = (enc, iv, authTag) => {
const decipher = crypto.createDecipheriv(ALGO, key, iv);
decipher.setAuthTag(authTag);
let str = decipher.update(enc, 'base64', 'utf8');
str += decipher.final('utf8');
return str;
};
return {
encrypt,
decrypt,
};
};
const KEY = Buffer.from(crypto.randomBytes(32), 'utf8');
const aesCipher = aes256gcm(KEY);
const [encrypted, iv, authTag] = aesCipher.encrypt('hello, world');
const decrypted = aesCipher.decrypt(encrypted, iv, authTag);
console.log({ KEY, encrypted, iv, authTag, decrypted }); // 'hello, world'
@youngkiu
Copy link
Author

{
  KEY: <Buffer 2c 93 f3 ed 8c ff 0d 7e 37 93 9d ff 24 7e a7 68 63 40 c0 fc 80 b9 8b f3 0e 0b 9f 41 8d e8 e4 c7>,
  encrypted: 'FqGBk1eZPN6JYHHE',
  iv: <Buffer c9 1d 16 3b fa a4 58 27 66 cc d2 f7>,
  authTag: <Buffer c5 5b c3 f9 a1 ac a9 c7 70 1d 9c 86 c9 36 ec 01>,
  decrypted: 'hello, world'
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment