Skip to content

Commit

Permalink
Merge pull request rails#40429 from natematykiewicz/openssl_fixed_len…
Browse files Browse the repository at this point in the history
…gth_secure_compare

Speed up `ActiveSupport::SecurityUtils.fixed_length_secure_compare`
  • Loading branch information
rafaelfranca committed Oct 22, 2020
2 parents 8d96647 + 5017b92 commit 7eb855b
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 7eb855b

Please sign in to comment.