-1

I am quite new in node. I have read that is recommended to use Crypto for hashing and salting the password to be not visible..but actual I am a little confused how to use it!!?? and what is the function that compares between the input password and the stored hashing password?!! Could you please help me in using Crypto??


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);
    .....
Sergey Kaunov
  • 140
  • 1
  • 8
amani rose
  • 121
  • 1
  • 9
  • 2
    I would use something like `bcryptjs` or `argon2` which include library functions for hashing and compare and help avoid issues with writing your own (which is easy to get wrong or less right) – Joe Nov 23 '19 at 19:33
  • Does this answer your question? [Node.js hashing of passwords](https://stackoverflow.com/questions/14015677/node-js-hashing-of-passwords) – tevemadar Nov 10 '22 at 13:26

1 Answers1

3

I find it very usefull to read the node documentation on crypto:

This is how I use it with files:

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'));
        })
    });
}

For hashing a password this would be ok:

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');
}

But don't use md5 for hashing passwords, use sha256.

Then you would put this hash in your database, get it from your database, hash the given password again and compare it to the hash in the database.

If you want even better security you would concatenate some constant string you generated once to the password. For example:

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');
}

I hope this helped, good luck!

Laurent Dhont
  • 1,012
  • 1
  • 9
  • 22