在nodejs中创建类似System.Web.Helpers.Crypto.HashPassword(ASP.NET)的



如何使用RFC 2898进行密码哈希https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/gg538287(v=vs.111(在nodejs中?

我的nodejs应用程序使用的是SQL server的一个表,该表的密码字段由ASP.NET的Crypto.HashPassword散列,所以我需要在nodejs中创建相同的函数来进行比较。

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

我用它来比较普通密码和散列密码。它工作得很好!

最新更新