Skip to content

Instantly share code, notes, and snippets.

@cararemixed
Created July 17, 2010 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cararemixed/479111 to your computer and use it in GitHub Desktop.
Save cararemixed/479111 to your computer and use it in GitHub Desktop.
zero:Scratch brian$ ruby --version # Should be similar on all versions of MRI
ruby 1.9.3dev (2010-06-30 trunk 28489) [x86_64-darwin10.4.0]
zero:Scratch brian$ ruby secure_cmp.rb
Rehearsal ------------------------------------------
binary 4.020000 0.000000 4.020000 ( 4.012945)
hash 2.180000 0.000000 2.180000 ( 2.187391)
--------------------------------- total: 6.200000sec
user system total real
binary 4.010000 0.010000 4.020000 ( 4.003827)
hash 2.180000 0.000000 2.180000 ( 2.186023)
The comparison with a hash doesn't need a salt value because of the inability to control the output of secure hash functions like SHA1. One could add a secret salt as well if they were paranoid or wanted to use less secure hash functions like MD5 with known payload exploits (though one could also use a shortcut on payload size if one is okay with letting that info leak).
require 'digest/sha1'
require 'benchmark'
N = 1_000_000
a = "xxyyrrttbbvv"
b = "112233445566"
Benchmark.bmbm do |test|
test.report("binary") {
N.times {
next unless a.bytesize == b.bytesize
l = a.unpack "C#{a.bytesize}"
res = 0
b.each_byte { |b| res |= b ^ l.shift }
res == 0
}
}
test.report("hash") {
N.times {Digest::SHA1.digest(a) == Digest::SHA1.digest(b)}
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment