Can I properly get a salt with Node.js crypto.getRandomValues method?

32 Views Asked by At

I am trying to generate a hashed password using the Scrypt algorithm. The issue is that I'm not sure if I am generating a random / unique salt properly. In the crypto.getRandomValues(new Uint8Array(64)) I assume to be generating a random set up to 64 characters. In the next parameter I'm setting my desired length, which is 32, converting back to a string becomes a random password with the length of 64. Am I doing this correct?

Here comes the code:

import { scrypt } from 'crypto';

  public createUser = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const { password } = req.body;

      // https://nodejs.org/docs/latest-v20.x/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback
      // https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
      scrypt(password, crypto.getRandomValues(new Uint8Array(64)), 32, async (err, derivedKey) => {
        const userToCreate = {
          password: derivedKey.toString('hex'),
          email: req.body['email'],
          username: req.body['username'],
        };

        const createdUser = await this.usersService.createUser(userToCreate);
        const response: ClientResponseInterface = {
          data: createdUser,
          error: false,
          message: 'Created a new user.',
          code: 200,
        };
        res.status(response.code).json(response);
      });
    } catch (error) {
      // Let Express handle the error for now:
      if (error instanceof Error) {
        next(`\x1b[41m[${error.name}]\x1b[0m:\t${error.message}`);
      } else {
        next(error);
      }
    }
  };
0

There are 0 best solutions below