Skip to content

Commit eef5579

Browse files
committed
added support for different crypto api
1 parent e5ea4d4 commit eef5579

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

lib/mongo/password_safe.ex

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,36 @@ defmodule Mongo.PasswordSafe do
3535
{:reply, password |> decrypt(key), data}
3636
end
3737

38-
defp encrypt(plaintext, key) do
39-
iv = :crypto.strong_rand_bytes(16) # create random Initialisation Vector
40-
ciphertext = :crypto.crypto_one_time(:aes_256_ctr, key, iv, plaintext, true)
41-
iv <> ciphertext # "return" iv & ciphertext
42-
end
38+
if String.to_integer(System.otp_release()) < 22 do
39+
40+
@aad "AES256GCM"
41+
42+
defp encrypt(plaintext, key) do
43+
iv = :crypto.strong_rand_bytes(16) # create random Initialisation Vector
44+
{ciphertext, tag} = :crypto.block_encrypt(:aes_gcm, key, iv, {@aad, to_string(plaintext), 16})
45+
iv <> tag <> ciphertext # "return" iv with the cipher tag & ciphertext
46+
end
47+
48+
defp decrypt(ciphertext, key) do
49+
<<iv::binary-16, tag::binary-16, ciphertext::binary>> = ciphertext
50+
:crypto.block_decrypt(:aes_gcm, key, iv, {@aad, ciphertext, tag})
51+
end
52+
53+
else
54+
defp encrypt(plaintext, key) do
55+
iv = :crypto.strong_rand_bytes(16) # create random Initialisation Vector
56+
ciphertext = :crypto.crypto_one_time(:aes_256_ctr, key, iv, plaintext, true)
57+
iv <> ciphertext # "return" iv & ciphertext
58+
end
59+
60+
defp decrypt(ciphertext, key) do
61+
<<iv::binary-16, ciphertext::binary>> = ciphertext
62+
:crypto.crypto_one_time(:aes_256_ctr, key, iv, ciphertext, false)
63+
end
4364

44-
defp decrypt(ciphertext, key) do
45-
<<iv::binary-16, ciphertext::binary>> = ciphertext
46-
:crypto.crypto_one_time(:aes_256_ctr, key, iv, ciphertext, false)
4765
end
4866

4967
defp generate_key() do
5068
:crypto.strong_rand_bytes(32)
5169
end
52-
5370
end

0 commit comments

Comments
 (0)