0

如何在nodejs中使用像https://docs.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/gg538287(v=vs.111)这样的RFC 2898来制作密码哈希?

我的 nodejs 应用程序正在使用一个 SQL 服务器表,其中密码字段由 ASP.NET 的 Crypto.HashPassword 散列,所以我需要在 nodejs 中创建相同的函数来比较它。

4

1 回答 1

0
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;
};

我用它来比较普通密码和散列密码。它运作良好!

于 2018-07-15T14:45:07.063 回答