Skip to content

Commit

Permalink
Add test to ensure constant time comparison stays constant
Browse files Browse the repository at this point in the history
Co-authored-by: arrtchiu <arrtchiu@gmail.com>
  • Loading branch information
bdewater and arrtchiu committed Aug 18, 2019
1 parent 794d4d3 commit f38987e
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions test/test_ossl.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true
require_relative "utils"

require 'benchmark'

if defined?(OpenSSL)

class OpenSSL::OSSL < OpenSSL::SSLTestCase
Expand All @@ -20,6 +22,22 @@ def test_memcmp?
refute OpenSSL.memcmp?("aaa", "bbb")
refute OpenSSL.memcmp?("aaa", "bbbb")
end

def test_memcmp_timing
# ensure using consttime_bytes_eq? takes almost exactly the same amount of time to compare two
# different strings.
# NOTE: this test may be susceptible to noise if the system running the tests is otherwise under
# load.
a = "x"*512_000
b = "#{a}y"
c = "y#{a}"
a = "#{a}x"

n = 10_000
a_b_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, b) } }.real
a_c_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, c) } }.real
assert_in_delta(a_b_time, a_c_time, 0.1, "memcmp? timing test failed")
end
end

end

0 comments on commit f38987e

Please sign in to comment.