Created
August 31, 2012 02:37
-
-
Save boronine/3548196 to your computer and use it in GitHub Desktop.
Password hashing and verifying with Node.js standard library (PBKDF2 + SHA1)
This file contains 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
hasher {}, (err, result) -> | |
# Save as hex strings | |
user.salt = result.salt.toString 'hex' | |
user.key = result.key.toString 'hex' | |
user.save -> | |
postmark.send | |
From: "you@example.com" | |
To: user.email | |
Subject: "Thank you for signing up with Example.com" | |
TextBody: "Your temporary password is #{result.plaintext}" |
This file contains 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
crypto = require 'crypto' | |
hasher = (opts, callback) -> | |
# Generate random 8-character base64 password if none provided | |
if not opts.plaintext | |
return crypto.randomBytes 6, (err, buf) -> | |
callback err if err | |
opts.plaintext = buf.toString 'base64' | |
hasher opts, callback | |
# Generate random 512-bit salt if no salt provided | |
if not opts.salt | |
return crypto.randomBytes 64, (err, buf) -> | |
callback err if err | |
opts.salt = buf | |
hasher opts, callback | |
# Node.js PBKDF2 forces sha1 | |
opts.hash = 'sha1' | |
opts.iterations = opts.iterations ? 10000 | |
crypto.pbkdf2 opts.plaintext, opts.salt, opts.iterations, 64, (err, key) -> | |
callback err if err | |
opts.key = new Buffer(key) | |
callback null, opts |
This file contains 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
hasher {plaintext: 'secret'}, (err, result) -> | |
# Save as hex strings | |
user.salt = result.salt.toString 'hex' | |
user.key = result.key.toString 'hex' | |
user.save() |
This file contains 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
# Hex string to Binary | |
salt = new Buffer user.salt, 'hex' | |
hasher {plaintext: 'secret', salt: salt}, (err, result) -> | |
if user.key == result.key.toString 'hex' | |
console.log 'Success!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BLOG POST: http://boronine.com/2012/08/30/Strong-Password-Hashing-with-Node-Standard-Library/