]> Entropealabs - wampex.git/commitdiff
add compare_secure crypto function
authorChristopher Coté <chris@entropealabs.com>
Sat, 18 Sep 2021 00:52:44 +0000 (20:52 -0400)
committerChristopher Coté <chris@entropealabs.com>
Sat, 18 Sep 2021 00:52:44 +0000 (20:52 -0400)
lib/crypto.ex

index c20b100e642b2ae1e48c81d6c07808b79b1c17bd..7731f67ac16744bb0e4b4f5000b07439ff9086b7 100644 (file)
@@ -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