From: Christopher Coté Date: Sat, 18 Sep 2021 00:52:44 +0000 (-0400) Subject: add compare_secure crypto function X-Git-Url: http://git.entropealabs.com/?a=commitdiff_plain;h=4aa0ae5272886dffed6a2ed5472f31ebb94f88b3;p=wampex.git add compare_secure crypto function --- diff --git a/lib/crypto.ex b/lib/crypto.ex index c20b100..7731f67 100644 --- a/lib/crypto.ex +++ b/lib/crypto.ex @@ -1,5 +1,8 @@ defmodule Wampex.Crypto do @moduledoc false + + use Bitwise + def hash_challenge(key, data) do :hmac |> :crypto.mac(:sha256, key, data) @@ -17,4 +20,24 @@ defmodule Wampex.Crypto do |> :crypto.strong_rand_bytes() |> Base.encode64() end + + def compare_secure(x, y) when is_binary(x) and is_binary(y) do + compare_secure(String.to_charlist(x), String.to_charlist(y)) + end + + def compare_secure(x, y) when is_list(x) and is_list(y) do + if length(x) == length(y) do + compare_secure(x, y, 0) + else + false + end + end + + def compare_secure(_, _), do: false + + defp compare_secure([x | rest_x], [y | rest_y], acc) do + compare_secure(rest_x, rest_y, bxor(x, y) |> bor(acc)) + end + + defp compare_secure([], [], acc), do: acc == 0 end