Last active
April 15, 2016 19:35
-
-
Save certainty/32c7d5733a31d7a03b28f5ab0ebbb205 to your computer and use it in GitHub Desktop.
constant_time_compare
This file contains hidden or 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
defmodule Compare do | |
use Bitwise | |
@type bytes :: [char] | |
@spec constant_time(bytes, bytes) :: boolean | |
def constant_time(x, y) when length(x) != length(y), do: false | |
def constant_time(x, y), do: do_constant_time(x, y, 0) | |
defp do_constant_time([], _, acc), do: acc == 0 | |
defp do_constant_time([x|xs], [y|ys], acc), do: do_constant_time(xs, ys, bor(acc, bxor(x,y))) | |
end |
This file contains hidden or 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
defmodule Compare2 do | |
use Bitwise | |
@type bytes :: [char] | |
@spec constant_time(bytes, bytes) :: boolean | |
def constant_time(x, y) when length(x) != length(y), do: false | |
def constant_time(x, y) when is_list(x) and is_list(y), do: do_constant_time(x, y) | |
defp do_constant_time(x, y) do | |
(Enum.zip(x, y) |> Enum.reduce(0, &compare_bytes/2)) == 0 | |
end | |
defp compare_bytes({x, y}, acc), do: bor(acc, bxor(x, y)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment