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 5de75398c495f109772b622291362a98bc6c21d1 1 parent d2cf33e
Kuba Kuźma qoobaa authored NZKoz committed

Showing 1 changed file with 6 additions and 9 deletions. Show diff stats Hide diff stats

  1. +6 9 activesupport/lib/active_support/message_verifier.rb
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

0 comments on commit 5de7539

Please sign in to comment.
Something went wrong with that request. Please try again.