Skip to content

Commit

Permalink
Speed up ActiveSupport::SecurityUtils.fixed_length_secure_compare
Browse files Browse the repository at this point in the history
by using `OpenSSL.fixed_length_secure_compare`, if available.
  • Loading branch information
natematykiewicz committed Oct 22, 2020
1 parent 8183963 commit 5017b92
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
5 changes: 5 additions & 0 deletions 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
Expand Down
19 changes: 13 additions & 6 deletions activesupport/lib/active_support/security_utils.rb
Expand Up @@ -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

Expand Down

0 comments on commit 5017b92

Please sign in to comment.