1 # frozen_string_literal: true
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)
18 elsif salt&.include?("!")
19 algorithm, iterations, salt = salt.split("!")
20 size = Base64.strict_decode64(hash).length
21 ActiveSupport::SecurityUtils.secure_compare(hash, pbkdf2(candidate, salt, iterations.to_i, size, algorithm))
25 def self.upgrade?(hash, _salt)
26 format = Argon2::HashFormat.new(hash)
28 format.variant != FORMAT.variant ||
29 format.version != FORMAT.version ||
30 format.t_cost != FORMAT.t_cost ||
31 format.m_cost != FORMAT.m_cost ||
32 format.p_cost != FORMAT.p_cost
33 rescue Argon2::ArgonHashFail
37 def self.valid?(hash, salt)
38 Argon2::HashFormat.valid_hash?(hash) || salt&.include?("!")
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)