Skip to content

Instantly share code, notes, and snippets.

@cipriantarta
Created December 12, 2018 10:31
Show Gist options
  • Save cipriantarta/50293ebe663e42379ea9cb644fe3b083 to your computer and use it in GitHub Desktop.
Save cipriantarta/50293ebe663e42379ea9cb644fe3b083 to your computer and use it in GitHub Desktop.
AES encryption + decryption
var aesjs = require('aes-js');
var exports = module.exports = {}
const blockSize = 16;
function pad(s) {
const len = blockSize - s.length % blockSize;
return s.padEnd(blockSize, String.fromCharCode(len));
}
function unpad(data) {
const code = data[data.length - 1];
return data.slice(0, -code);
}
function encrypt(data, secret) {
if (secret === undefined) {
throw Error('Secret key not provided');
}
const iv = crypto.randomBytes(blockSize);
const key = secret.split('').map(chr => chr.charCodeAt());
const bytes = aesjs.utils.utf8.toBytes(pad(data));
const aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
let result = aesCbc.encrypt(bytes);
const buffer = Buffer.concat([iv, result]);
return buffer.toString('base64');
}
function decrypt(data, secret) {
if (secret === undefined) {
throw Error('Secret key not provided');
}
const key = secret.split('').map(chr => chr.charCodeAt());
buffer = Buffer.from(data, 'base64')
iv = buffer.slice(0, blockSize);
cbc = new aesjs.ModeOfOperation.cbc(key, iv);
let result = cbc.decrypt(buffer.slice(blockSize));
result = unpad(result);
return aesjs.utils.utf8.fromBytes(result);
}
exports.encrypt = encrypt;
exports.decrypt = decrypt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment