Skip to content

Commit 84130f8

Browse files
authored
Fallback when hash_equals fails for missing openssl support (#45)
1 parent 3ff0bfe commit 84130f8

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

lib/plug/crypto.ex

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -133,22 +133,30 @@ defmodule Plug.Crypto do
133133
# TODO: remove when we require OTP 25.0
134134
if Code.ensure_loaded?(:crypto) and function_exported?(:crypto, :hash_equals, 2) do
135135
defp crypto_hash_equals(x, y) do
136-
:crypto.hash_equals(x, y)
136+
# Depending on the linked OpenSSL library hash_equals is available.
137+
# If not, we fall back to the legacy implementation.
138+
try do
139+
:crypto.hash_equals(x, y)
140+
rescue
141+
# Still can throw "Unsupported CRYPTO_memcmp"
142+
ErlangError ->
143+
legacy_secure_compare(x, y, 0)
144+
end
137145
end
138146
else
139147
defp crypto_hash_equals(x, y) do
140148
legacy_secure_compare(x, y, 0)
141149
end
150+
end
142151

143-
defp legacy_secure_compare(<<x, left::binary>>, <<y, right::binary>>, acc) do
144-
import Bitwise
145-
xorred = bxor(x, y)
146-
legacy_secure_compare(left, right, acc ||| xorred)
147-
end
152+
defp legacy_secure_compare(<<x, left::binary>>, <<y, right::binary>>, acc) do
153+
import Bitwise
154+
xorred = bxor(x, y)
155+
legacy_secure_compare(left, right, acc ||| xorred)
156+
end
148157

149-
defp legacy_secure_compare(<<>>, <<>>, acc) do
150-
acc === 0
151-
end
158+
defp legacy_secure_compare(<<>>, <<>>, acc) do
159+
acc === 0
152160
end
153161

154162
@doc """

0 commit comments

Comments
 (0)