使用用户/密码保护NEDB数据库



i'am评估nedb对一个proyect的使用。但是看来本地不支持用户/密码保护。有什么方法可以使用用户和密码保护NEDB数据库?

这是一个示例。

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()
    },
})

请注意,这仅使用加密密钥保护数据库,而不是用户名/密码组合。

有关更多详细信息,请参见https://gist.github.com/jordanbtucker/e9dde26b372048cf2cbe85a6aa9618de

您可以使用NEDB钩afterSerializationbeforeDeserialization进行加密&解密数据

示例:

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;
    }
});

最新更新