我正在评估nedb在一个项目中的用途。但它似乎本身并不支持用户/密码保护。有什么方法可以用用户和密码保护nedb数据库吗?
答案 0 :(得分:0)
您可以使用nedb hook afterSerialization
,beforeDeserialization
来加密&解密数据
示例:
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;
}
});
答案 1 :(得分:0)
这是一个例子。
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()
},
})
请注意,这仅使用加密密钥而不是用户名/密码组合来保护数据库。