PERF: Use OpenSSL::KDF for Pbkdf2 implementation ()

This was introduced to the standard library in Ruby 2.4. In my testing, it produces the same result, and is around 8x faster than our pure-ruby implementation
This commit is contained in:
David Taylor 2023-04-05 17:00:05 +01:00 committed by GitHub
parent b24c35d887
commit d3e5251704
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 8 additions and 27 deletions

@ -71,8 +71,6 @@ gem "rails_multisite"
gem "fast_xs", platform: :ruby
gem "xorcist"
gem "fastimage"
gem "aws-sdk-s3", require: false

@ -514,7 +514,6 @@ GEM
hashdiff (>= 0.4.0, < 2.0.0)
webrick (1.7.0)
websocket (1.2.9)
xorcist (1.1.3)
xpath (3.2.0)
nokogiri (~> 1.8)
yaml-lint (0.1.2)
@ -666,7 +665,6 @@ DEPENDENCIES
webdrivers
webmock
webrick
xorcist
yaml-lint
yard

@ -1,28 +1,13 @@
# frozen_string_literal: true
# Note: This logic was originally extracted from the Pbkdf2 gem to fix Ruby 2.0
# issues, but that gem has gone stale so we won't be returning to it.
require "openssl"
require "xorcist"
class Pbkdf2
def self.hash_password(password, salt, iterations, algorithm = "sha256")
h = OpenSSL::Digest.new(algorithm)
u = ret = prf(h, password, salt + [1].pack("N"))
2.upto(iterations) do
u = prf(h, password, u)
Xorcist.xor!(ret, u)
end
ret.bytes.map { |b| ("0" + b.to_s(16))[-2..-1] }.join("")
end
protected
def self.prf(hash_function, password, data)
OpenSSL::HMAC.digest(hash_function, password, data)
def self.hash_password(password, salt, iterations, algorithm = "sha256", length: 32)
OpenSSL::KDF.pbkdf2_hmac(
password,
salt: salt,
iterations: iterations,
length: length,
hash: algorithm,
).unpack1("H*")
end
end