Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created February 21, 2014 15:34
Show Gist options
  • Save jcoglan/9136362 to your computer and use it in GitHub Desktop.
Save jcoglan/9136362 to your computer and use it in GitHub Desktop.
var crypto = require("crypto")
var User = function(attributes) {
this._attributes = attributes || {}
}
User.KEY_LENGTH = 32
User.WORK_FACTOR = 20000
User.prototype.setPassword = function(password, callback) {
var attrs = this._attributes
attrs.salt = crypto.randomBytes(User.KEY_LENGTH)
crypto.pbkdf2(password, attrs.salt, User.WORK_FACTOR, User.KEY_LENGTH,
function(error, key) {
attrs.password = key.toString("hex")
if (callback) callback(null)
})
}
User.prototype.checkPassword = function(password, callback) {
var attrs = this._attributes,
diff = 0
crypto.pbkdf2(password, attrs.salt, User.WORK_FACTOR, User.KEY_LENGTH,
function(error, key) {
key = key.toString("hex")
for (var i = 0, n = key.length; i < n; i++) {
diff |= key.charCodeAt(i) ^ attrs.password.charCodeAt(i)
}
var error = (diff === 0) ? null : new Error("Access denied")
callback(error)
})
}
module.exports = User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment