-
-
Save mbenitez01/8ddb7aee1b1727345db95fc85b2a8442 to your computer and use it in GitHub Desktop.
A really tiny JSON encrypted-and-compressed datastore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dead simple compressed and encrypted datastore | |
var crypto = require('crypto'); | |
var zlib = require('zlib'); | |
var fs = require('fs'); | |
var stream = require('stream'); | |
// Load the session store from #{filename} and decrypt it using #{method} with | |
// the key #{key}. | |
// @param filename {String} filename | |
// @param key the encryption key, can be a string or buffer | |
// @param method (default = "aes-256-cbc") the encryption method to use | |
// @returns {Stream} a stream containing your JSON data | |
module.exports.load = function(filename, key, method) { | |
method = method || 'aes-256-cbc'; | |
var decipher = crypto.createDecipher(method, key); | |
var file = fs.createReadStream(filename); | |
var unpack = zlib.createGunzip(); | |
return file.pipe(unpack).pipe(decipher); | |
}; | |
// Save the given data into filename and encrypt / compress it. | |
// @param data {Object} JSON-serializable data | |
// @param filename {String} filename | |
// @param key the encryption key, can be a string or buffer | |
// @param method (default = "aes-256-cbc") the encryption method to use | |
// @returns {Writable Stream} the file stream | |
module.exports.save = function(data, filename, key, method) { | |
method = method || 'aes-256-cbc'; | |
var cipher = crypto.createCipher(method, key); | |
var file = fs.createWriteStream(filename); | |
var pack = zlib.createGzip(); | |
var s = new stream.Readable(); | |
data = JSON.stringify(data); | |
s.push(data); | |
s.push(null); | |
return s.pipe(cipher).pipe(pack).pipe(file); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment