【问题标题】:nodejs - save account information inside .env file or in client side databasenodejs - 将帐户信息保存在 .env 文件或客户端数据库中
【发布时间】:2021-07-29 02:53:36
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js vue.js dotenv nedb


    【解决方案1】:

    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, SECRET, iv);
            const plaintextBytes = Buffer.concat([decipher.update(data), decipher.final()]);
            return plaintextBytes.toString('utf8');
        },
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 2019-04-29
      • 1970-01-01
      • 2019-10-27
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多