Created
January 27, 2018 16:19
-
-
Save chrisdl/a1de3f44249e1ebeb3b09658f5e18ad4 to your computer and use it in GitHub Desktop.
youre welcome.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require("crypto"); | |
class Db { | |
constructor(users={}) { | |
this.users = users; | |
} | |
// Expects passwordPayload to be a string of the form 'salt$passwordHash' | |
// Where the '$' is used as a separator. | |
storeUser(username, passwordPayload) { | |
this.users[username] = passwordPayload; | |
} | |
getUserPassword(username) { | |
let hash = this.users[username]; | |
return { | |
salt: hash.substr(0, hash.indexOf('$')), | |
passwordHash: hash.substr(hash.indexOf('$') + 1) | |
}; | |
} | |
} | |
const db = new Db(); | |
// STUDENT CODE STARTS HERE ------------ | |
const hashPassword = (password, salt) => { | |
const passwordHash = crypto.pbkdf2Sync(password, salt, 70451, 64, 'sha256'); | |
return passwordHash.toString('hex'); | |
}; | |
const saveUser = (username, password) => { | |
const salt = crypto.randomBytes(64).toString('hex'); | |
const passwordHash = hashPassword(password, salt); | |
const payload = `${salt}$${passwordHash}`; | |
db.storeUser(username, payload); | |
}; | |
// Return true if authenticated, false otherwise. | |
const isUserAuthenticated = (username, password) => { | |
let payload; | |
try { | |
payload = db.getUserPassword(username); | |
} catch (error) { | |
if (!(error instanceof TypeError)) throw error; | |
// insert work | |
hashPassword('notARealPassword', 'mySaltIsbetterThanMyPepper'); | |
return false; | |
} | |
const { salt, passwordHash } = payload; | |
return comparePasswords(password, salt, passwordHash); | |
}; | |
// returns true if passwords match, otherwise false. | |
const comparePasswords = (plaintextPassword, salt, passwordHashFromDb) => { | |
return hashPassword(plaintextPassword, salt) === passwordHashFromDb; | |
}; | |
// STUDENT CODE ENDS HERE ------------ | |
saveUser('[email protected]', '123456qwerty'); | |
console.time('1') | |
console.log(isUserAuthenticated('[email protected]', 'HelloWorld!')) // false | |
console.timeEnd('1') | |
console.time('2') | |
console.log(isUserAuthenticated('[email protected]', 'HelloWorld!')) // false | |
console.timeEnd('2') | |
console.time('3') | |
console.log(isUserAuthenticated('[email protected]', 'HelloWorld!')) // false | |
console.timeEnd('3') | |
console.time('4') | |
console.log(isUserAuthenticated('[email protected]', '123456qwerty')) // true | |
console.timeEnd('4') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment