From 5017b92362914ed724f0403dbccfea2aa5e7153c Mon Sep 17 00:00:00 2001 From: Nate Matykiewicz Date: Thu, 22 Oct 2020 00:03:19 -0500 Subject: [PATCH] Speed up `ActiveSupport::SecurityUtils.fixed_length_secure_compare` by using `OpenSSL.fixed_length_secure_compare`, if available. --- activesupport/CHANGELOG.md | 5 +++++ .../lib/active_support/security_utils.rb | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 956c4a74b6333..6695fd2e85d5f 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,8 @@ +* Speed up `ActiveSupport::SecurityUtils.fixed_length_secure_compare` by using + `OpenSSL.fixed_length_secure_compare`, if available. + + *Nate Matykiewicz* + * `ActiveSupport::Cache::MemCacheStore` now checks `ENV["MEMCACHE_SERVERS"]` before falling back to `"localhost:11211"` if configured without any addresses. ```ruby diff --git a/activesupport/lib/active_support/security_utils.rb b/activesupport/lib/active_support/security_utils.rb index acd598cf50fb3..4eeac896f7625 100644 --- a/activesupport/lib/active_support/security_utils.rb +++ b/activesupport/lib/active_support/security_utils.rb @@ -6,14 +6,21 @@ module SecurityUtils # # The values compared should be of fixed length, such as strings # that have already been processed by HMAC. Raises in case of length mismatch. - def fixed_length_secure_compare(a, b) - raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize - l = a.unpack "C#{a.bytesize}" + if defined?(OpenSSL.fixed_length_secure_compare) + def fixed_length_secure_compare(a, b) + OpenSSL.fixed_length_secure_compare(a, b) + end + else + def fixed_length_secure_compare(a, b) + raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize - res = 0 - b.each_byte { |byte| res |= byte ^ l.shift } - res == 0 + l = a.unpack "C#{a.bytesize}" + + res = 0 + b.each_byte { |byte| res |= byte ^ l.shift } + res == 0 + end end module_function :fixed_length_secure_compare