]> git.openstreetmap.org Git - rails.git/blob - lib/password_hash.rb
Move html_safe declaration for user_mailer from layout to helper
[rails.git] / lib / password_hash.rb
1 require "argon2"
2 require "base64"
3 require "digest/md5"
4 require "openssl"
5 require "securerandom"
6
7 module PasswordHash
8   FORMAT = Argon2::HashFormat.new(Argon2::Password.create(""))
9
10   def self.create(password)
11     hash = Argon2::Password.create(password)
12     [hash, nil]
13   end
14
15   def self.check(hash, salt, candidate)
16     if Argon2::HashFormat.valid_hash?(hash)
17       Argon2::Password.verify_password(candidate, hash)
18     elsif salt.nil?
19       ActiveSupport::SecurityUtils.secure_compare(hash, Digest::MD5.hexdigest(candidate))
20     elsif salt.include?("!")
21       algorithm, iterations, salt = salt.split("!")
22       size = Base64.strict_decode64(hash).length
23       ActiveSupport::SecurityUtils.secure_compare(hash, pbkdf2(candidate, salt, iterations.to_i, size, algorithm))
24     else
25       ActiveSupport::SecurityUtils.secure_compare(hash, Digest::MD5.hexdigest(salt + candidate))
26     end
27   end
28
29   def self.upgrade?(hash, _salt)
30     format = Argon2::HashFormat.new(hash)
31
32     format.variant != FORMAT.variant ||
33       format.version != FORMAT.version ||
34       format.t_cost != FORMAT.t_cost ||
35       format.m_cost != FORMAT.m_cost ||
36       format.p_cost != FORMAT.p_cost
37   rescue Argon2::ArgonHashFail
38     true
39   end
40
41   def self.pbkdf2(password, salt, iterations, size, algorithm)
42     digest = OpenSSL::Digest.new(algorithm)
43     pbkdf2 = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, size, digest)
44     Base64.strict_encode64(pbkdf2)
45   end
46 end