UNPKG

secure-keys-dc

Version:

Updates secure-keys module to use Cipheriv and aes-256-cbc

77 lines (64 loc) 2.16 kB
'use strict'; var crypto = require('crypto'); var json = { stringify: function (obj, replacer, spacing) { return JSON.stringify(obj, replacer || null, spacing || 2) }, parse: JSON.parse }; module.exports = Secure; /** * @constructor * Simple Object used to serialize and deserialize */ function Secure(opts) { opts = opts || {}; this.secret = typeof opts !== 'string' ? opts.secret : opts; this.format = opts.format || json; this.alg = opts.alg || 'aes-256-cbc'; if (!this.secret) throw new Error('Secret is a required option'); } Secure.prototype.encrypt = function encrypt(data, callback) { var self = this; return Object.keys(data).reduce(function (acc, key) { var value = self.format.stringify(data[key]); acc[key] = { alg: self.alg, value: cipherConvert(value, { alg: self.alg, secret: self.secret, encs: { input: 'utf8', output: 'hex' } }) }; return acc; }, {}); }; Secure.prototype.decrypt = function decrypt(data, callback) { var self = this; return Object.keys(data).reduce(function (acc, key) { var encs = { input: 'hex', output: 'utf8' } const textParts = data[key].value.split(':'); const iv = new Buffer(textParts.shift(), encs.input); const encryptedText = new Buffer(textParts.join(':'), encs.input); const decipher = crypto.createDecipheriv(data[key].alg, self.secret, iv); let decrypted = decipher.update(encryptedText); // Returns buffer decrypted = Buffer.concat([decrypted, decipher.final()]); //decipher.final() also returns buffer acc[key] = self.format.parse(decrypted.toString(encs.output)); return acc; }, {}); }; // // ### function cipherConvert (contents, opts) // Returns the result of the cipher operation // on the contents contents. // function cipherConvert(contents, opts) { var encs = opts.encs; const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-cbc', opts.secret, iv); let crypted = cipher.update(contents, encs.input, encs.output); crypted += cipher.final(encs.output); return `${iv.toString('hex')}:${crypted.toString()}`; }