Skip to content

Commit

Permalink
Add secure_compare to Rack::Utils
Browse files Browse the repository at this point in the history
Conflicts:
	test/spec_utils.rb
  • Loading branch information
raggi committed Feb 7, 2013
1 parent 8ded2f7 commit feea59c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/rack/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,18 @@ def byte_ranges(env, size)
end
module_function :byte_ranges

# Constant time string comparison.
def secure_compare(a, b)
return false unless bytesize(a) == bytesize(b)

l = a.unpack("C*")

r, i = 0, -1
b.each_byte { |v| r |= v ^ l[i+=1] }
r == 0
end
module_function :secure_compare

# Context allows the use of a compatible middleware at different points
# in a request handling stack. A compatible middleware must define
# #context which should take the arguments env and app. The first of which
Expand Down
5 changes: 5 additions & 0 deletions test/spec_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,11 @@ def kcodeu
Rack::Utils.bytesize("FOO\xE2\x82\xAC").should.equal 6
end

should "should perform constant time string comparison" do
Rack::Utils.secure_compare('a', 'a').should.equal true
Rack::Utils.secure_compare('a', 'b').should.equal false
end

should "return status code for integer" do
Rack::Utils.status_code(200).should.equal 200
end
Expand Down

0 comments on commit feea59c

Please sign in to comment.