2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2021-05-21 09:43:47 +08:00
|
|
|
# Note: This logic was originally extracted from the Pbkdf2 gem to fix Ruby 2.0
|
2020-09-01 03:20:44 +08:00
|
|
|
# issues, but that gem has gone stale so we won't be returning to it.
|
2013-03-06 20:12:16 +08:00
|
|
|
|
|
|
|
require 'openssl'
|
2020-09-01 03:20:44 +08:00
|
|
|
require 'xorcist'
|
|
|
|
require 'xorcist/refinements'
|
2013-03-06 20:12:16 +08:00
|
|
|
|
|
|
|
class Pbkdf2
|
2020-09-01 03:20:44 +08:00
|
|
|
using Xorcist::Refinements
|
2013-03-06 20:12:16 +08:00
|
|
|
|
2013-07-23 09:36:01 +08:00
|
|
|
def self.hash_password(password, salt, iterations, algorithm = "sha256")
|
|
|
|
|
2014-01-21 01:33:40 +08:00
|
|
|
h = OpenSSL::Digest.new(algorithm)
|
2013-07-23 09:36:01 +08:00
|
|
|
|
2013-03-06 20:12:16 +08:00
|
|
|
u = ret = prf(h, password, salt + [1].pack("N"))
|
|
|
|
|
2013-07-23 09:36:01 +08:00
|
|
|
2.upto(iterations) do
|
2013-03-06 20:12:16 +08:00
|
|
|
u = prf(h, password, u)
|
2020-09-01 03:20:44 +08:00
|
|
|
ret.xor!(u)
|
2013-03-06 20:12:16 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
ret.bytes.map { |b| ("0" + b.to_s(16))[-2..-1] }.join("")
|
|
|
|
end
|
|
|
|
|
2013-07-23 09:36:01 +08:00
|
|
|
protected
|
2013-03-06 20:12:16 +08:00
|
|
|
|
|
|
|
def self.prf(hash_function, password, data)
|
|
|
|
OpenSSL::HMAC.digest(hash_function, password, data)
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|