Skip to content

Instantly share code, notes, and snippets.

@jpotts18
Created December 13, 2018 19:02
Show Gist options
  • Save jpotts18/8be5172fc219264abcc0a6f999e4675c to your computer and use it in GitHub Desktop.
Save jpotts18/8be5172fc219264abcc0a6f999e4675c to your computer and use it in GitHub Desktop.
Node AES CBC Example
// AES RFC - https://tools.ietf.org/html/rfc3602
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
// generate with crypto.randomBytes(256/8).toString('hex')
const key = process.env.AES_KEY;
const IV_LENGTH = 16;
const encrypt = (text) => {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};
const decrypt = (text) => {
const [iv, encryptedText] = text.split(':').map(part => Buffer.from(part, 'hex'));
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key, 'hex'), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
exports.encrypt = encrypt;
exports.decrypt = decrypt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment