Skip to content

Commit 0c1a445

Browse files
bdewaterarrtchiu
andcommitted
Add test to ensure constant time comparison stays constant
Co-authored-by: arrtchiu <arrtchiu@gmail.com>
1 parent 4169467 commit 0c1a445

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

test/test_ossl.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# frozen_string_literal: true
22
require_relative "utils"
33

4+
require 'benchmark'
5+
46
if defined?(OpenSSL)
57

68
class OpenSSL::OSSL < OpenSSL::SSLTestCase
@@ -23,6 +25,22 @@ def test_memcmp?
2325
refute OpenSSL.memcmp?("aaa", "bbb")
2426
assert_raises(ArgumentError) { OpenSSL.memcmp?("aaa", "bbbb") }
2527
end
28+
29+
def test_memcmp_timing
30+
# ensure using consttime_bytes_eq? takes almost exactly the same amount of time to compare two
31+
# different strings.
32+
# NOTE: this test may be susceptible to noise if the system running the tests is otherwise under
33+
# load.
34+
a = "x" * 512_000
35+
b = "#{a}y"
36+
c = "y#{a}"
37+
a = "#{a}x"
38+
39+
n = 10_000
40+
a_b_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, b) } }.real
41+
a_c_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, c) } }.real
42+
assert_in_delta(a_b_time, a_c_time, 0.25, "memcmp? timing test failed")
43+
end
2644
end
2745

2846
end

0 commit comments

Comments
 (0)