Created
August 25, 2023 03:37
-
-
Save Freaky/062d1210f377455b83b075ab3570fdd8 to your computer and use it in GitHub Desktop.
A faster pure Ruby constant-time secure compare
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fixed_length_secure_compare(a, b) | |
raise ArgumentError, 'length mismatch' unless a.bytesize == b.bytesize | |
res = 0 | |
if a.bytesize >= 4 && a.bytesize % 4 == 0 | |
ai = a.unpack "L*" | |
bi = b.unpack "L*" | |
ai.each { |int| res |= int ^ bi.shift } | |
else | |
ab = a.bytes | |
b.each_byte { |byte| res |= byte ^ ab.shift } | |
end | |
res == 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Against a SHA256 hexdigest:
Might have been useful prior to
OpenSSL.fixed_length_secure_compare
- now it's just a bit of fun.