8   FORMAT = Argon2::HashFormat.new(Argon2::Password.create(""))
 
  10   def self.create(password)
 
  11     hash = Argon2::Password.create(password)
 
  15   def self.check(hash, salt, candidate)
 
  16     if Argon2::HashFormat.valid_hash?(hash)
 
  17       Argon2::Password.verify_password(candidate, hash)
 
  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))
 
  25       ActiveSupport::SecurityUtils.secure_compare(hash, Digest::MD5.hexdigest(salt + candidate))
 
  29   def self.upgrade?(hash, _salt)
 
  30     format = Argon2::HashFormat.new(hash)
 
  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
 
  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)