Skip to content

Instantly share code, notes, and snippets.

@bllohar
Created September 25, 2017 06:52
Show Gist options
  • Save bllohar/28ee29b3304d8bf6dbc11d1b16b00130 to your computer and use it in GitHub Desktop.
Save bllohar/28ee29b3304d8bf6dbc11d1b16b00130 to your computer and use it in GitHub Desktop.
Nedb Encryption & Decryption
var Datastore = require('nedb')
const path = require('path')
var crypto = require('crypto');
var assert = require('assert');
var algorithm = 'aes256';
var key = 'password';
var db = {}
db.bookinghistories = new Datastore({
filename : path.join(__dirname, 'data/bookinghistories.db'),
autoload: true,
afterSerialization: function (doc) {
console.log(doc);
var encrypted =doc;
try{
var ef;
if(JSON.parse(doc) && isNaN(doc)){
var cipher = crypto.createCipher(algorithm, key);
encrypted=cipher.update(JSON.stringify(doc), 'utf8', 'hex') + cipher.final('hex');
ef = encrypted;
console.log("Ser" +encrypted);
return encrypted;
}
}catch(e){
}
da=encrypted;
},
beforeDeserialization : function(doc) {
console.log(doc);
if (doc != undefined && doc != "") {
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(doc, 'hex', 'utf8') + decipher.final('utf8');
console.log("decipher" + decrypted);
return decrypted;
}
//console.log("decipher2 " + da);
return da;
}
});
@RHeijnen
Copy link

RHeijnen commented Jun 15, 2020

@jordanbtucker
Hey Jordan, I know this really is not the place - but care to share more about that ? I am trying to achieve the same thing but running into several issues originating from my lack of experience in crypto.

An basic explenation would be very much appreciated!

@jordanbtucker
Copy link

@RHeijnen I created my own gist. It has two examples: one that prompts the user for a password each time the app starts, and one that stores the password in the system keychain. Both examples are heavily documented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment