Skip to content

Commit

Permalink
Ruby 1.9: fix MessageVerifier#secure_compare
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy committed Sep 8, 2009
1 parent a43ef24 commit 8a2cfe9
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions activesupport/lib/active_support/message_verifier.rb
Expand Up @@ -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

Expand Down

0 comments on commit 8a2cfe9

Please sign in to comment.