To ensure the confidentiality and integrity of sensitive information by using secure encryption methods.
defmodule MyApp do
def encode(data) do
{:ok, hex_data} = data |> to_string() |> Base.encode16()
hex_data
end
end
In this insecure code example, sensitive data is being encoded to hexadecimal using Base.encode16(). Although this does obfuscate the data, it does not provide any security because it can easily be decoded back into its original form.
defmodule MyApp do
def encode(data) do
# Here is an example key, but for real-world applications, you should use a secure way to store and access keys
key = :crypto.strong_rand_bytes(32)
iv = :crypto.strong_rand_bytes(16)
{:ok, encrypted_data} = :crypto.block_encrypt(:aes_gcm, key, iv, to_string(data))
encrypted_data
end
end
In this secure code example, the AES encryption algorithm is used to encrypt the data. This provides both confidentiality and integrity for the data. It's important to manage the encryption keys securely, as the security of the encrypted data depends on the security of the key.