nodejs - 在 .env 文件或客户端数据库中保存帐户信息

问题描述

我创建了一个简单的 nodejs 应用程序,它将使用 express 进行一些文件处理操作。我将使用 pkg 打包最终的应用程序,这意味着该应用程序将以只读模式访问打包的资源。既然我想实现登录系统和一次性帐户创建,那么最好的方法是什么?该应用程序将打开一个浏览器选项卡,该选项卡将为 UI 运行一个 vuejs 应用程序。我正在考虑通过在 vue 应用程序中实现它来使用 nedb-promises,但存储在其中的数据可供所有人访问,因此登录将变得不安全。有没有办法加密/解密 nedb-promises 中存储的数据?

我想使用的另一种解决方案是运行一次性帐户创建并将创建的帐户信息存储在 .env 文件中,该文件将在 te 应用程序将运行的文件夹中创建。使用此方法如何散列密码和帐户数据,以及在启动应用程序时使用用户将输入的凭据检查它们?

解决方法

NeDB 有两个函数,分别称为 beforeDeserializationafterSerialization。这些可用于在使用 crypto 模块读取和写入数据库时​​加密和解密数据。

const crypto    = require('crypto');
const Datastore = require('nedb-promises');

const ALGORITHM = 'aes-256-cbc'
const BLOCK_SIZE = 16
const SECRET = 'SECRET'

const database = new Datastore({
    filename: 'database.db',autoload: true,afterSerialization (plaintext) {
        // Encryption

        const iv = crypto.randomBytes(BLOCK_SIZE);
        const cipher = crypto.createCipheriv(ALGORITHM,SECRET,iv);
        const ciphertext = Buffer.concat([iv,cipher.update(plaintext),cipher.final()]);
        return ciphertext.toString('base64');
    },beforeDeserialization (ciphertext) {
        // Decryption

        const ciphertextBytes = Buffer.from(ciphertext,'base64');
        const iv = ciphertextBytes.slice(0,BLOCK_SIZE);
        const data = ciphertextBytes.slice(BLOCK_SIZE);
        const decipher = crypto.createDecipheriv(ALGORITHM,iv);
        const plaintextBytes = Buffer.concat([decipher.update(data),decipher.final()]);
        return plaintextBytes.toString('utf8');
    },});

您希望 SECRET 变量是存储在 .env 文件中的随机生成的字符串