Skip to content

Commit

Permalink
Allow iodata in AAD
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Mar 10, 2023
1 parent 060ee3a commit d1ae2e5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/plug/crypto/message_encryptor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ defmodule Plug.Crypto.MessageEncryptor do
It defaults to "A128GCM" for backwards compatibility.
"""
def encrypt(message, aad \\ "A128GCM", secret, sign_secret)
when is_binary(message) and is_binary(aad) and byte_size(secret) > 0 and
when is_binary(message) and (is_binary(aad) or is_list(aad)) and byte_size(secret) > 0 and
is_binary(sign_secret) do
aes128_gcm_encrypt(message, aad, secret, sign_secret)
rescue
Expand All @@ -45,7 +45,7 @@ defmodule Plug.Crypto.MessageEncryptor do
Decrypts a message using authenticated encryption.
"""
def decrypt(encrypted, aad \\ "A128GCM", secret, sign_secret)
when is_binary(encrypted) and is_binary(aad) and byte_size(secret) > 0 and
when is_binary(encrypted) and (is_binary(aad) or is_list(aad)) and byte_size(secret) > 0 and
is_binary(sign_secret) do
aes128_gcm_decrypt(encrypted, aad, secret, sign_secret)
rescue
Expand Down
8 changes: 7 additions & 1 deletion test/plug/crypto/message_encryptor_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ defmodule Plug.Crypto.MessageEncryptorTest do

test "it encrypts/decrypts a message" do
data = <<0, "hełłoworld", 0>>
encrypted = ME.encrypt(<<0, "hełłoworld", 0>>, "right aad", @right, @right)
encrypted = ME.encrypt(data, "right aad", @right, @right)

decrypted = ME.decrypt(encrypted, "right aad", @wrong, @wrong)
assert decrypted == :error
Expand All @@ -29,6 +29,12 @@ defmodule Plug.Crypto.MessageEncryptorTest do
assert decrypted == {:ok, data}
end

test "it encrypts/decrypts with iodata aad" do
data = <<0, "hełłoworld", 0>>
encrypted = ME.encrypt(data, ["right", ?\s, "aad"], @right, @right)
assert ME.decrypt(encrypted, ["right", ?\s, "aad"], @right, @right) == {:ok, data}
end

test "it uses only the first 32 bytes to encrypt/decrypt" do
data = <<0, "helloworld", 0>>
encrypted = ME.encrypt(<<0, "helloworld", 0>>, @large, @large)
Expand Down

0 comments on commit d1ae2e5

Please sign in to comment.