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 "fast_xs", platform: :ruby
gem "xorcist"
gem "fastimage" gem "fastimage"
gem "aws-sdk-s3", require: false gem "aws-sdk-s3", require: false

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

@ -1,28 +1,13 @@
# frozen_string_literal: true # 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 class Pbkdf2
def self.hash_password(password, salt, iterations, algorithm = "sha256") def self.hash_password(password, salt, iterations, algorithm = "sha256", length: 32)
h = OpenSSL::Digest.new(algorithm) OpenSSL::KDF.pbkdf2_hmac(
password,
u = ret = prf(h, password, salt + [1].pack("N")) salt: salt,
iterations: iterations,
2.upto(iterations) do length: length,
u = prf(h, password, u) hash: algorithm,
Xorcist.xor!(ret, u) ).unpack1("H*")
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)
end end
end end