2

I'am evaluating the use of nedb for one proyect. But it seems that natively it's don't support user/password protection. There is any way to protect an nedb database with user and password?

CStff
  • 361
  • 2
  • 10

2 Answers2

4

Here's an example.

const crypto = require('crypto')
const Datastore = require('nedb')

const ALGORITHM = 'aes-256-cbc'
const BLOCK_SIZE = 16
const KEY_SIZE = 32

// Generate a random key.
// If you want to use a password, use scrypt to generate the key instead.
const key = crypto.randomBytes(KEY_SIZE)

const db = new Datastore({
    filename: 'encrypted.db',

    afterSerialization (plaintext) {
        // Encryption

        // Generate random IV.
        const iv = crypto.randomBytes(BLOCK_SIZE)

        // Create cipher from key and IV.
        const cipher = crypto.createCipheriv(ALGORITHM, key, iv)

        // Encrypt record and prepend with IV.
        const ciphertext = Buffer.concat([iv, cipher.update(plaintext), cipher.final()])

        // Encode encrypted record as Base64.
        return ciphertext.toString('base64')
    },

    beforeDeserialization (ciphertext) {
        // Decryption

        // Decode encrypted record from Base64.
        const ciphertextBytes = Buffer.from(ciphertext, 'base64')

        // Get IV from initial bytes.
        const iv = ciphertextBytes.slice(0, BLOCK_SIZE)

        // Get encrypted data from remaining bytes.
        const data = ciphertextBytes.slice(BLOCK_SIZE)

        // Create decipher from key and IV.
        const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)

        // Decrypt record.
        const plaintextBytes = Buffer.concat([decipher.update(data), decipher.final()])

        // Encode record as UTF-8.
        return plaintextBytes.toString()
    },
})

Note that this only protects the database with an encryption key, not a username/password combination.

For more detailed information, see https://gist.github.com/jordanbtucker/e9dde26b372048cf2cbe85a6aa9618de

jordanbtucker
  • 5,768
  • 2
  • 30
  • 43
1

You can use nedb hooksafterSerialization, beforeDeserialization to encrypt & decrypt data

example :

var db = new Datastore({

    filename : path.join(__dirname, 'data/anything.db'), 
    autoload: true,
    afterSerialization: function (doc) {
            // encription usig AES or any algo
    },

    beforeDeserialization : function(doc) {
        // encription usig AES and or algo with same key
        return doc;
    }
});
Bheru Lal Lohar
  • 880
  • 9
  • 17