Skip to content
This repository
Browse code

ruby 1.9 friendly secure_compare

Signed-off-by: Michael Koziarski <michael@koziarski.com>
  • Loading branch information...
commit b22c951e7adabe8d37ee2804487c267d5e2006b1 1 parent ff2eb2d
Kuba Kuźma authored September 11, 2009 NZKoz committed September 12, 2009
15  activesupport/lib/active_support/message_verifier.rb
@@ -38,24 +38,21 @@ def generate(value)
38 38
     end
39 39
     
40 40
     private
41  
-      if "foo".respond_to?(:force_encoding)
  41
+      if "foo".respond_to?(:bytesize)
42 42
         # constant-time comparison algorithm to prevent timing attacks
  43
+        # > 1.8.6 friendly version
43 44
         def secure_compare(a, b)
44  
-          a = a.force_encoding(Encoding::BINARY)
45  
-          b = b.force_encoding(Encoding::BINARY)
46  
-
47  
-          if a.length == b.length
  45
+          if a.bytesize == b.bytesize
48 46
             result = 0
49  
-            for i in 0..(a.length - 1)
50  
-              result |= a[i].ord ^ b[i].ord
51  
-            end
  47
+            j = b.each_byte
  48
+            a.each_byte { |i| result |= i ^ j.next }
52 49
             result == 0
53 50
           else
54 51
             false
55 52
           end
56 53
         end
57 54
       else
58  
-        # For 1.8
  55
+        # For <= 1.8.6
59 56
         def secure_compare(a, b)
60 57
           if a.length == b.length
61 58
             result = 0

2 notes on commit b22c951

Sam Ruby

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'
Please sign in to comment.
Something went wrong with that request. Please try again.