Skip to content

Instantly share code, notes, and snippets.

@certainty
Last active April 15, 2016 19:35
Show Gist options
  • Save certainty/32c7d5733a31d7a03b28f5ab0ebbb205 to your computer and use it in GitHub Desktop.
Save certainty/32c7d5733a31d7a03b28f5ab0ebbb205 to your computer and use it in GitHub Desktop.
constant_time_compare
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
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