title: Faster constant-time string comparison in Ruby
body: <p>I'm trying to compare an authentication token supplied by a user with an authentication token stored on my server.</p>
  
  <p>The most obvious way to do this is just to use <code>==</code>, but that potentially creates a timing attack.</p>
  
  <p>To mitigate that I wrote this secure comparison function:</p>
  
  <pre><code># string comparison that leaks no information about the strings.
  # loosely based on https://github.com/rack/rack/blob/master/lib/rack/utils.rb
  # and http://security.stackexchange.com/questions/49849/timing-safe-string-comparison-avoiding-length-leak
  def secure_compare(a, b)
    l = a.unpack("C*")
  
    i = 0
    r |= a.length - b.length # fail if the lengths are different
    b.each_byte do |v|
      r |= v ^ l[i]
      i = (i + 1) % a.length # make sure we compare on all bytes of b, even if a is shorter.
    end
    r == 0
  end
  </code></pre>
  
  <p>The only problem is that this is <em>really</em> slow: it adds 180ms to a 60-80ms page load.</p>
  
  <p>Is there a faster way to do constant time string comparisons? Is there a more standardised way to do it?</p>
  
  <p>EDIT: I'm using the following script to benchmark different solutions, fwiw - <a href="https://gist.github.com/daxtens/a3a59f163f08f9b447bb">https://gist.github.com/daxtens/a3a59f163f08f9b447bb</a> - it shows how <code>==</code> can bail out early, leaking information, and how <code>secure_compare</code> is several orders of magnitude slower than <code>==</code>.</p>
  
  <p>EDIT 2: Just to be perfectly clear, what I am trying to achieve is a function <code>secure_compare(secret, untrusted_input)</code>, where the time taken to execute depends entirely on <code>untrusted_input</code>, and not on <code>secret</code>. I also want this function to be no more than a couple of orders of magnitude worse than <code>==</code>. The provided function has the desired timing dependency, but it's way too slow.</p>