louischatriot / nedb

The JavaScript Database, for Node.js, nw.js, electron and the browser
MIT License
13.49k stars 1.03k forks source link

nedb encryption & decryption issue #529

Open bllohar opened 7 years ago

bllohar commented 7 years ago

facing an issue with nedb data encryption & decryption

Here is the gist: https://gist.github.com/bllohar/28ee29b3304d8bf6dbc11d1b16b00130

above code works fine it encrypt and all

But once I close the app and reopen it all data is gone.

JamesMGreene commented 7 years ago

The code in the gist is definitely not working.

This if check, in particular, will literally NEVER pass:

if(JSON.parse(doc) && isNaN(doc)){
isaacherrera47 commented 6 years ago

Try to change method to eval your json. This works for me:

afterSerialization: function (doc) {
        console.log('AFTER SERIALIZATION')
        console.log('A - DOC : ' + doc)
        if (isJson(doc)) {
            let cipher = crypto.createCipher(algorithm, key);
            encrypted = cipher.update(JSON.stringify(doc), 'utf8', 'hex') + cipher.final('hex');
            console.log("Ser " + encrypted);
            return encrypted;
        }
        return doc;
    },
    beforeDeserialization: function (doc) {
        console.log('BEFORE SERIALIZATION')
        console.log('B - DOC : ' + doc)

        let decipher = crypto.createDecipher(algorithm, key);

        try {
            let decrypted = decipher.update(doc, 'hex', 'utf8') + decipher.final('utf8');
            console.log("decipher" + JSON.parse(decrypted));
            return JSON.parse(decrypted);
        } catch (e) {
            console.log('Catched error ' + doc)
            return doc
        }
    } 

Where my function isJson works as follows:

function isJson(item) {
    item = typeof item !== "string" ?
        JSON.stringify(item) :
        item;

    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }

    if (typeof item === "object" && item !== null) {
        return true;
    }

    return false;
}

I added logs to draw a trace in the console. I think the key of functionality is at JSON.parse on beforeSerialization because if you don't parse it, the output would be like {"\key"\ : "\value"} , so this is not a valid json to store in nedb.

PD: Sorry for my bad english :P