@@ -35,19 +35,36 @@ defmodule Mongo.PasswordSafe do
35
35
{ :reply , password |> decrypt ( key ) , data }
36
36
end
37
37
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
43
64
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 )
47
65
end
48
66
49
67
defp generate_key ( ) do
50
68
:crypto . strong_rand_bytes ( 32 )
51
69
end
52
-
53
70
end
0 commit comments