Search code examples
javascriptnode.jsmean-stackcryptojs

NodeJS stuck at cryto.pbkdf2Sync function


So I am generating a password hash using a random salt string and a password string in a MEAN Stack application. The program successfully generates the random salt and prints it out on the console. However, it gets stuck at the pbkdf2Sync function and fails to move forward.

This is my code:

const crypto = require('crypto');

UserSchema.methods.setPassword = function(password){
  console.log('start');
  this.salt = crypto.randomBytes(16).toString('hex');
  console.log(this.salt);
  this.hash = crypto.pbkdf2Sync(new Buffer.alloc(password),  new Buffer.alloc(this.salt), 1000, 64, 'sha512').toString('hex');
  console.log(this.hash);
};

The output results in:

start
ac09ae82b1fbb5b01257b5fa72bfc8614

And then the program just gets stuck here.

As far as I know, the function is not deprecated. How should I proceed


Solution

  • const crypto = require('crypto');
    
    const hash = (password) => {
      console.log('start');
      const salt = crypto.randomBytes(16).toString('hex');
      console.log(salt);
      const hash = crypto
        .pbkdf2Sync(
          new Buffer.alloc(password.length),
          new Buffer.alloc(salt.length),
          1000,
          64,
          'sha512'
        )
        .toString('hex');
      console.log(hash);
    };
    
    hash('hello world');
    

    This worked for me, essentially alloc is looking for the number of bytes (size to allocate in memory), a string wouldn't work here.

    If you're looking to use password and salt as filled Buffers (with values), then use the second argument (fill), in the case of password: new Buffer.alloc(password.length, password).

    Instead, using the .length to return the amount of bytes (size of string), this generated the "correct" output:

    start
    55387a56bd8ff87ac05be698d938ef04
    ab3d65e9e6341a924c752a77b8dc6b78f1e6db5d31df7dd0cc534039dd9662a97bcaf0b959fe78248a49859c7952ddb25d66840f052b27ef1ab60b9446c0c9fd
    

    Ref: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding