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 7a48cd6 commit 91f65b7
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
3 changes: 2 additions & 1 deletion activesupport/Rakefile
Expand Up @@ -88,7 +88,8 @@ task :release => [ :package ] do
end


require 'lib/active_support/values/time_zone'
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib"
require 'active_support/values/time_zone'

namespace :tzinfo do
desc "Update bundled tzinfo gem. Only copies the subset of classes and definitions required to support Rails time zone features."
Expand Down
77 changes: 77 additions & 0 deletions activesupport/lib/active_support/message_verifier.rb
@@ -0,0 +1,77 @@
module ActiveSupport
# MessageVerifier makes it easy to generate and verify messages which are signed
# to prevent tampering.
#
# This is useful for cases like remember-me tokens and auto-unsubscribe links where the
# session store isn't suitable or available.
#
# Remember Me:
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
#
# In the authentication filter:
#
# id, time = @verifier.verify(cookies[:remember_me])
# if time < Time.now
# self.current_user = User.find(id)
# end
#
class MessageVerifier
class InvalidSignature < StandardError; end

def initialize(secret, digest = 'SHA1')
@secret = secret
@digest = digest
end

def verify(signed_message)
data, digest = signed_message.split("--")
if secure_compare(digest, generate_digest(data))
Marshal.load(ActiveSupport::Base64.decode64(data))
else
raise InvalidSignature
end
end

def generate(value)
data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
"#{data}--#{generate_digest(data)}"
end

private
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
end
end

def generate_digest(data)
require 'openssl' unless defined?(OpenSSL)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), @secret, data)
end
end
end

0 comments on commit 91f65b7

Please sign in to comment.