File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11# frozen_string_literal: true
22require_relative "utils"
33
4+ require 'benchmark'
5+
46if defined? ( OpenSSL )
57
68class 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
2644end
2745
2846end
You can’t perform that action at this time.
0 commit comments