Created
September 25, 2017 06:52
-
-
Save bllohar/28ee29b3304d8bf6dbc11d1b16b00130 to your computer and use it in GitHub Desktop.
Nedb Encryption & Decryption
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
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; | |
} | |
}); |
@jordanbtucker thanks
@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!
@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
@kailashyogeshwar85 I don't store the key. I use scryptsy to generate the key with a password each time the app is started.
If you do need to store the key, you can use a package like keytar to store the key using the system's keychain/credential vault.