如何在节点中使用加密?

问题描述 投票:0回答:1

我在节点上退出了。我已经读过,建议使用Crypto加密和盐化密码以使其不可见..但实际上,我有点困惑如何使用它!在输入的密码和存储的哈希密码之间进行比较的功能是什么?!您能帮我使用Crpyto吗?


app.post("/signup", async (req, res, next) => {
    const { username, password} = req.body;
    if (!username && !password ) {
      res.json({
        success: false,
        message: "Complete your Sign up "
      });
    }
    const query = `INSERT INTO Users (username ,password) VALUES ('${username}','${password}') `;
    const student = await db.run(query);
    .....
node.js
1个回答
2
投票

我发现阅读有关加密的节点文档非常有用:

这是我将其用于文件的方式:

const hash = crypto.createHash("md5");

function createHash(filePath) {
    const hash = crypto.createHash("md5");

    const readStream = fs.createReadStream(filePath);
    readStream.on('data', (data) => {
        hash.update(data);
    });

    return new Promise((resolve, reject) => {
        readStream.on('end', () => {
            resolve(hash.digest('hex'));
        })
    });
}

对于散列密码,没关系:

const hash = crypto.createHash("md5");
function hashPassword(password) {
    //replace md5 with sha256 or another algorithm
    const hash = crypto.createHash("md5");
    hash.update(password);
    return hash.digest('hex');
}

但是不要将md5用于哈希密码,请使用sha256。

然后,您将该散列放入数据库中,从数据库中获取它,再次对给定的密码进行散列,并将其与数据库中的散列进行比较。

如果您想要更好的安全性,可以将一次生成的一些常量字符串连接到密码。例如:

const fixedString = "dfgd5fgd6g5df6g5!u(è§è'"; // make this as complicated as possible.

function hashPassword(password) {


    //concatenate this to the password
    password += fixedString;

    const hash = crypto.createHash("sha256");
    hash.update(password);
    return hash.digest('hex');
}

我希望这会有所帮助,祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.