1 # frozen_string_literal: true
10 FORMAT = Argon2::HashFormat.new(Argon2::Password.create(""))
12 def self.create(password)
13 hash = Argon2::Password.create(password)
17 def self.check(hash, salt, candidate)
18 if Argon2::HashFormat.valid_hash?(hash)
19 Argon2::Password.verify_password(candidate, hash)
21 ActiveSupport::SecurityUtils.secure_compare(hash, Digest::MD5.hexdigest(candidate))
22 elsif salt.include?("!")
23 algorithm, iterations, salt = salt.split("!")
24 size = Base64.strict_decode64(hash).length
25 ActiveSupport::SecurityUtils.secure_compare(hash, pbkdf2(candidate, salt, iterations.to_i, size, algorithm))
27 ActiveSupport::SecurityUtils.secure_compare(hash, Digest::MD5.hexdigest(salt + candidate))
31 def self.upgrade?(hash, _salt)
32 format = Argon2::HashFormat.new(hash)
34 format.variant != FORMAT.variant ||
35 format.version != FORMAT.version ||
36 format.t_cost != FORMAT.t_cost ||
37 format.m_cost != FORMAT.m_cost ||
38 format.p_cost != FORMAT.p_cost
39 rescue Argon2::ArgonHashFail
43 def self.pbkdf2(password, salt, iterations, size, algorithm)
44 digest = OpenSSL::Digest.new(algorithm)
45 pbkdf2 = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, size, digest)
46 Base64.strict_encode64(pbkdf2)