Skip to content

Commit d43fe02

Browse files
committed
Improve encrypt + decrypt robustness
1 parent ea3bb1f commit d43fe02

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

lib/cadet_web/helpers/ai_comments_helpers.ex

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,25 +10,24 @@ defmodule CadetWeb.AICommentsHelpers do
1010
secret when is_binary(secret) and byte_size(secret) >= 16 ->
1111
key = binary_part(secret, 0, min(32, byte_size(secret)))
1212

13-
case Base.decode64(encrypted_key) do
14-
{:ok, decoded} ->
15-
case :binary.split(decoded, <<"|">>, [:global]) do
16-
[iv, tag, ciphertext] ->
17-
case :crypto.crypto_one_time_aead(:aes_gcm, key, iv, ciphertext, "", tag, false) do
18-
plain_text when is_binary(plain_text) -> {:ok, plain_text}
19-
_ -> {:decrypt_error, :decryption_failed}
20-
end
21-
13+
case String.split(encrypted_key, ":", parts: 3, trim: false) do
14+
[iv_b64, tag_b64, cipher_b64] ->
15+
with {:ok, iv} <- Base.decode64(iv_b64),
16+
{:ok, tag} <- Base.decode64(tag_b64),
17+
{:ok, ciphertext} <- Base.decode64(cipher_b64) do
18+
case :crypto.crypto_one_time_aead(:aes_gcm, key, iv, ciphertext, "", tag, false) do
19+
plain_text when is_binary(plain_text) -> {:ok, plain_text}
20+
_ -> {:decrypt_error, :decryption_failed}
21+
end
22+
else
2223
_ ->
23-
{:error, :invalid_format}
24+
Logger.error("Failed to decode one of the components of the encrypted key")
25+
{:decrypt_error, :invalid_format}
2426
end
2527

2628
_ ->
27-
Logger.error(
28-
"Failed to decode encrypted key, is it a valid AES-256 key of 16, 24 or 32 bytes?"
29-
)
30-
31-
{:decrypt_error, :decryption_failed}
29+
Logger.error("Encrypted key format is invalid")
30+
{:decrypt_error, :invalid_format}
3231
end
3332

3433
_ ->
@@ -57,7 +56,8 @@ defmodule CadetWeb.AICommentsHelpers do
5756
)
5857

5958
# Store both the IV, ciphertext and tag
60-
encrypted = Base.encode64(iv <> "|" <> tag <> "|" <> ciphertext)
59+
encrypted =
60+
Base.encode64(iv) <> ":" <> Base.encode64(tag) <> ":" <> Base.encode64(ciphertext)
6161
else
6262
{:error, :invalid_encryption_key}
6363
end

0 commit comments

Comments
 (0)