Skip to content

Instantly share code, notes, and snippets.

@jasonbrice
Created February 25, 2015 20:52
Show Gist options
  • Save jasonbrice/819fa5165a89673a9855 to your computer and use it in GitHub Desktop.
Save jasonbrice/819fa5165a89673a9855 to your computer and use it in GitHub Desktop.
JavaScript implementation of Microsoft.AspNet.Identity.Crypto.VerifyHashedPassword
// Reference https://gist.github.com/trailmax/553ea84d4d0e2e20fcd7
function VerifyHashedPassword(password, hashedPwd) {
// NodeJS implementation of crypto
var crypto = require('crypto');
var hexChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
var hashedPasswordBytes = new Buffer(hashedPwd, 'base64');
var saltString = "";
var storedSubKeyString = "";
// build strings of octets for the salt and the stored key
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];
}
}
// Generate derived bytes
var nodeCrypto = crypto.pbkdf2Sync(new Buffer(password), new Buffer(saltString, 'hex'), 1000, 256, 'sha1');
// Get a hex string of the derived bytes
var derivedKeyOctets = nodeCrypto.toString('hex').toUpperCase();
// The first 64 bytes of the derived key should match the stored sub key
if (derivedKeyOctets.indexOf(storedSubKeyString) === 0) {
console.log("Passwords match!");
return true;
} else {
console.log("Passwords DO NOT MATCH!");
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment