Skip to content

Commit

Permalink
ruby 1.9 friendly secure_compare
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Koziarski <michael@koziarski.com>
  • Loading branch information
Jakub Kuźma authored and NZKoz committed Sep 12, 2009
1 parent ff2eb2d commit b22c951
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions activesupport/lib/active_support/message_verifier.rb
Expand Up @@ -38,24 +38,21 @@ def generate(value)
end

private
if "foo".respond_to?(:force_encoding)
if "foo".respond_to?(:bytesize)
# constant-time comparison algorithm to prevent timing attacks
# > 1.8.6 friendly version
def secure_compare(a, b)
a = a.force_encoding(Encoding::BINARY)
b = b.force_encoding(Encoding::BINARY)

if a.length == b.length
if a.bytesize == b.bytesize
result = 0
for i in 0..(a.length - 1)
result |= a[i].ord ^ b[i].ord
end
j = b.each_byte
a.each_byte { |i| result |= i ^ j.next }
result == 0
else
false
end
end
else
# For 1.8
# For <= 1.8.6
def secure_compare(a, b)
if a.length == b.length
result = 0
Expand Down

2 comments on commit b22c951

@rubys
Copy link
Contributor

@rubys rubys commented on b22c951 Sep 12, 2009

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stack traceback for Ruby 1.8.7:

/home/rubys/git/awdwr/work/depot/vendor/rails/activesupport/lib/active_support/message_verifier.rb:47:in `each_byte'
/home/rubys/git/awdwr/work/depot/vendor/rails/activesupport/lib/active_support/message_verifier.rb:47:in `secure_compare'
/home/rubys/git/awdwr/work/depot/vendor/rails/activesupport/lib/active_support/message_verifier.rb:28:in `verify'
/home/rubys/git/awdwr/work/depot/vendor/rails/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb:170:in `unmarshal'

@rubys
Copy link
Contributor

@rubys rubys commented on b22c951 Sep 12, 2009

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.