Skip to content

Instantly share code, notes, and snippets.

@sled
Created November 17, 2015 08:25
Show Gist options
  • Save sled/495055011db3453051b5 to your computer and use it in GitHub Desktop.
Save sled/495055011db3453051b5 to your computer and use it in GitHub Desktop.
Constant time comparisons
# constant-time comparison algorithm to prevent timing attacks
def self.secure_compare(a, b)
return false if a.blank? || b.blank? || a.bytesize != b.bytesize
l = a.unpack "C#{a.bytesize}"
res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment