password_hash.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module PasswordHash
  3. include ApplicationLib
  4. # rubocop:disable Style/ModuleFunction
  5. extend self
  6. def crypt(password)
  7. argon2.create(password)
  8. end
  9. def verified?(pw_hash, password)
  10. Argon2::Password.verify_password(password, pw_hash, secret)
  11. rescue
  12. false
  13. end
  14. def crypted?(pw_hash)
  15. return false if !pw_hash
  16. return true if hashed_argon2?(pw_hash)
  17. return true if hashed_sha2?(pw_hash)
  18. false
  19. end
  20. def legacy?(pw_hash, password)
  21. return false if pw_hash.blank?
  22. return false if !password
  23. sha2?(pw_hash, password)
  24. end
  25. def hashed_sha2?(pw_hash)
  26. pw_hash.start_with?('{sha2}')
  27. end
  28. def hashed_argon2?(pw_hash)
  29. # taken from: https://github.com/technion/ruby-argon2/blob/7e1f4a2634316e370ab84150e4f5fd91d9263713/lib/argon2.rb#L33
  30. pw_hash =~ /^\$argon2i\$.{,112}/
  31. end
  32. def sha2(password)
  33. crypted = Digest::SHA2.hexdigest(password)
  34. "{sha2}#{crypted}"
  35. end
  36. private
  37. def sha2?(pw_hash, password)
  38. return false if !hashed_sha2?(pw_hash)
  39. pw_hash == sha2(password)
  40. end
  41. def argon2
  42. return @argon2 if @argon2
  43. @argon2 = Argon2::Password.new(secret: secret)
  44. end
  45. def secret
  46. Setting.get('application_secret')
  47. end
  48. end