Skip to content

Commit

Permalink
Move check for :crypto.hash_equals/2 to compile-time.
Browse files Browse the repository at this point in the history
  • Loading branch information
potatosalad committed Oct 5, 2023
1 parent de8598e commit c34c7da
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions lib/plug/crypto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ defmodule Plug.Crypto do
`Plug.Crypto.MessageEncryptor`, and `Plug.Crypto.MessageVerifier`.
"""

import Bitwise
alias Plug.Crypto.{KeyGenerator, MessageVerifier, MessageEncryptor}

@doc """
Expand Down Expand Up @@ -131,22 +130,25 @@ defmodule Plug.Crypto do
byte_size(left) == byte_size(right) and crypto_hash_equals(left, right)
end

defp crypto_hash_equals(x, y) do
# TODO: remove when we require OTP 25.0
if Code.ensure_loaded?(:crypto) and function_exported?(:crypto, :hash_equals, 2) do
# TODO: remove when we require OTP 25.0
if Code.ensure_loaded?(:crypto) and function_exported?(:crypto, :hash_equals, 2) do
defp crypto_hash_equals(x, y) do
:crypto.hash_equals(x, y)
else
end
else
defp crypto_hash_equals(x, y) do
legacy_secure_compare(x, y, 0)
end
end

defp legacy_secure_compare(<<x, left::binary>>, <<y, right::binary>>, acc) do
xorred = bxor(x, y)
legacy_secure_compare(left, right, acc ||| xorred)
end
defp legacy_secure_compare(<<x, left::binary>>, <<y, right::binary>>, acc) do
import Bitwise
xorred = bxor(x, y)
legacy_secure_compare(left, right, acc ||| xorred)
end

defp legacy_secure_compare(<<>>, <<>>, acc) do
acc === 0
defp legacy_secure_compare(<<>>, <<>>, acc) do
acc === 0
end
end

@doc """
Expand Down

0 comments on commit c34c7da

Please sign in to comment.