Skip to content

Instantly share code, notes, and snippets.

@emboss
Created October 20, 2011 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emboss/1300424 to your computer and use it in GitHub Desktop.
Save emboss/1300424 to your computer and use it in GitHub Desktop.
Using PBKDF2 with HMAC-SHA256 for storing passwords
p ="password"
#according to PKCS#5, should be at least 8 bytes. Public information, can be stored along with the pwd.
s = OpenSSL::Random.random_bytes(16)
c = 20000 # varies depending on how fast the system is, tweak until it takes "long enough"
digest = OpenSSL::Digest::SHA256.new
#should be >= the output size of the underlying hash function, but ">" doesn't improve security (says PKCS#5)
dk_len = digest.digest_length
#store the result for new passwords
value = OpenSSL::PKCS5.pbkdf2_hmac(p, s, c, dk_len, digest)
#Comparison with existing passwords
stored = #...
# We shouldn't do this (http://codahale.com/a-lesson-in-timing-attacks/)
#if value == stored
# So we need a comparison that takes always the same amount of time
def eql_time_compare(a, b)
unless a.size == b.size
return false
end
cmp = b.bytes.to_a
result = 0
a.bytes.each_with_index {|c, i|
result |= c ^ cmp[i]
}
result == 0
end
return eql_time_compare(stored, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment