首页 > 解决方案 > 如何将加密密码存储在 node.js 的环境变量中?

问题描述

所以这个想法很简单,但我不确定我是否做得正确。在我的应用程序中,我需要为某些数据库连接使用用户名/密码。信息存储在我的 .bashrc 文件中,并导出 env vars。我不想以明文形式存储它们,所以我想将它们加密存储。在运行时,我读取环境变量,解密并使用它们。

我目前拥有的是一个执行加密的node.js应用程序,代码片段:

    const crypto = require('crypto');

    const emailPassword = CLEAR_TEXT_PASSWORD;
    const algorithm = 'aes-192-cbc';
    const password = 'p3241';
    const key = crypto.scryptSync(password, 'salt', 24);
    const iv = Buffer.alloc(16, 0); 

    const cipher = crypto.createCipheriv(algorithm, key, iv);

    let encrypted = cipher.update(emailPassword, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    console.log(encrypted);

上面的结果成为我的环境变量。

现在在我的消费者应用程序中,要使用 env 变量,我有一个在使用前解密的反向例程。

看起来像

export const decipher = (input: string) : string => {
    const algorithm = 'aes-192-cbc';
    const password = 'p3241';

    const key = crypto.scryptSync(password, 'salt', 24);


    const iv = Buffer.alloc(16, 0); 

    const decipher = crypto.createDecipheriv(algorithm, key, iv);

    let decrypted = decipher.update(input, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    console.log(decrypted);
    return decrypted;
}

但我不知道加密/解密的所有参数在我的服务器代码中都是明文。

有没有更好的方法来做到这一点,还是我过于偏执?

标签: node.jspassword-encryption

解决方案


推荐阅读