Skip to content

Instantly share code, notes, and snippets.

@boronine
Created August 31, 2012 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boronine/3548196 to your computer and use it in GitHub Desktop.
Save boronine/3548196 to your computer and use it in GitHub Desktop.
Password hashing and verifying with Node.js standard library (PBKDF2 + SHA1)
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}"
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
hasher {plaintext: 'secret'}, (err, result) ->
# Save as hex strings
user.salt = result.salt.toString 'hex'
user.key = result.key.toString 'hex'
user.save()
# 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!'
@boronine
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment