Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stormbreakers
Last active October 30, 2017 07:05
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 stormbreakers/c8c5eebf9d63d004c3eab2fb892006f0 to your computer and use it in GitHub Desktop.
Save stormbreakers/c8c5eebf9d63d004c3eab2fb892006f0 to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
const alogrithm = 'aes-256-cbc';
const ENCRYPTION_KEY = '770A8A65DA156D24EE2A093277530142';
const IV_LENGTH = 16; // For AES, this is always 16
function encrypt(text) {
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv(alogrithm, new Buffer(ENCRYPTION_KEY), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
function decrypt(text) {
let textParts = text.split(':');
let iv = new Buffer(textParts.shift(), 'hex');
let encryptedText = new Buffer(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv(alogrithm, new Buffer(ENCRYPTION_KEY), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment