Strengthen password hashing algorithm
[rails.git] / lib / password_hash.rb
1 require "securerandom"
2 require "openssl"
3 require "base64"
4 require "digest/md5"
5
6 module PasswordHash
7   SALT_BYTE_SIZE = 32
8   HASH_BYTE_SIZE = 32
9   PBKDF2_ITERATIONS = 1000
10   DIGEST_ALGORITHM = "sha512"
11
12   def self.create(password)
13     salt = SecureRandom.base64(SALT_BYTE_SIZE)
14     hash = self.hash(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE, DIGEST_ALGORITHM)
15     return hash, [DIGEST_ALGORITHM, PBKDF2_ITERATIONS, salt].join("!")
16   end
17
18   def self.check(hash, salt, candidate)
19     if salt.nil?
20       candidate = Digest::MD5.hexdigest(candidate)
21     elsif salt =~ /!/
22       algorithm, iterations, salt = salt.split("!")
23       size = Base64.strict_decode64(hash).length
24       candidate = self.hash(candidate, salt, iterations.to_i, size, algorithm)
25     else
26       candidate = Digest::MD5.hexdigest(salt + candidate)
27     end
28
29     return hash == candidate
30   end
31
32 private
33
34   def self.hash(password, salt, iterations, size, algorithm)
35     digest = OpenSSL::Digest.new(algorithm)
36     pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac(password, salt, iterations, size, digest)
37     Base64.strict_encode64(pbkdf2)
38   end
39 end