Search code examples
asp.netnode.jsrfc2898

Create method like System.Web.Helpers.Crypto.HashPassword (ASP.NET) in nodejs?


How can I make password hash using RFC 2898 like https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/gg538287(v=vs.111) in nodejs?

My nodejs app are using a table of SQL server which have password field hashed by Crypto.HashPassword of ASP.NET, so I need create same function in nodejs to compare it.


Solution

  • const crypto = require('crypto');
    const hexChar = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
    const verifyHashedPassword = (password, hashedPwd) => {
      let saltString = '';
      let storedSubKeyString = '';
      const hashedPasswordBytes = new Buffer(hashedPwd, 'base64');
      for (var i = 1; i < hashedPasswordBytes.length; i++) {
        if (i > 0 && i <= 16) {
          saltString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f];
        }
        if (i > 0 && i > 16) {
          storedSubKeyString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f];
        }
      }
      const nodeCrypto = crypto.pbkdf2Sync(new Buffer(password), new Buffer(saltString, 'hex'), 1000, 256, 'sha1');
      const derivedKeyOctets = nodeCrypto.toString('hex').toUpperCase();
      return derivedKeyOctets.indexOf(storedSubKeyString) === 0;
    };
    

    I used that for compare plain password with hashed password. It's working well!