【发布时间】:2017-07-21 05:36:49
【问题描述】:
我正在评估 nedb 用于一个项目的情况。但似乎它本身不支持用户/密码保护。有什么方法可以使用用户和密码保护 nedb 数据库?
【问题讨论】:
我正在评估 nedb 用于一个项目的情况。但似乎它本身不支持用户/密码保护。有什么方法可以使用用户和密码保护 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 hooksafterSerialization, 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;
}
});
【讨论】: