Skip to content

Instantly share code, notes, and snippets.

@ashtonmeuser
Last active May 29, 2018 22:02
Show Gist options
  • Select an option

  • Save ashtonmeuser/7def97ad79c2bb8883cdc77fcd0be101 to your computer and use it in GitHub Desktop.

Select an option

Save ashtonmeuser/7def97ad79c2bb8883cdc77fcd0be101 to your computer and use it in GitHub Desktop.
AES-256 encryption and decryption
const crypto = require('crypto');
const encryptionSecret = Buffer.from(process.env.ENCRYPTION_SECRET);
const encrypt = (string) => {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', encryptionSecret, iv);
let encrypted = cipher.update(string);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
};
function decrypt(string) {
const stringParts = string.split(':');
const iv = Buffer.from(stringParts.shift(), 'hex');
const encryptedString = Buffer.from(stringParts.shift(), 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', encryptionSecret, iv);
let decrypted = decipher.update(encryptedString);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
module.exports = {
encrypt,
decrypt,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment