Permalink
Browse files

Ruby 1.9: fix MessageVerifier#secure_compare

  • Loading branch information...
1 parent a43ef24 commit 8a2cfe9de4e8b21fd5cecf21960f64a5c8a5a2a4 @jeremy jeremy committed Sep 8, 2009
Showing with 27 additions and 9 deletions.
  1. +27 −9 activesupport/lib/active_support/message_verifier.rb
View
36 activesupport/lib/active_support/message_verifier.rb
@@ -38,16 +38,34 @@ def generate(value)
end
private
- # constant-time comparison algorithm to prevent timing attacks
- def secure_compare(a, b)
- if a.length == b.length
- result = 0
- for i in 0..(a.length - 1)
- result |= a[i] ^ b[i]
+ if "foo".respond_to?(:force_encoding)
+ # constant-time comparison algorithm to prevent timing attacks
+ def secure_compare(a, b)
+ a = a.force_encoding(Encoding::BINARY)
+ b = b.force_encoding(Encoding::BINARY)
+
+ if a.length == b.length
+ result = 0
+ for i in 0..(a.length - 1)
+ result |= a[i].ord ^ b[i].ord
+ end
+ result == 0
+ else
+ false
+ end
+ end
+ else
+ # For 1.8
+ def secure_compare(a, b)
+ if a.length == b.length
+ result = 0
+ for i in 0..(a.length - 1)
+ result |= a[i] ^ b[i]
+ end
+ result == 0
+ else
+ false
end
- result == 0
- else
- false
end
end

0 comments on commit 8a2cfe9

Please sign in to comment.