File: securecompare.rb

package info (click to toggle)
ruby-securecompare 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 124 kB
  • sloc: ruby: 43; makefile: 3
file content (19 lines) | stat: -rw-r--r-- 464 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module SecureCompare
  require "securecompare/version"

  # constant-time comparison algorithm to prevent timing attacks; borrowed from ActiveSupport::MessageVerifier
  def secure_compare(a, b)
    return false unless a.bytesize == b.bytesize

    l = a.unpack("C#{a.bytesize}")

    res = 0
    b.each_byte { |byte| res |= byte ^ l.shift }
    res == 0
  end
  module_function :secure_compare

  class << self
    alias_method :compare, :secure_compare
  end
end