gpt4 book ai didi

node.js - 使用用户/密码保护 nedb 数据库。

转载 作者:行者123 更新时间:2023-12-03 12:17:37 24 4
gpt4 key购买 nike

我正在评估 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()
},
})

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

欲了解更多详细信息,请参阅https://gist.github.com/jordanbtucker/e9dde26b372048cf2cbe85a6aa9618de

关于node.js - 使用用户/密码保护 nedb 数据库。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com