Prevent predictable sequences of random numbers
defmodule MyApp.TokenGenerator do
def generate_token do
:random.seed(:erlang.now())
:random.uniform(100000)
end
end
This code is vulnerable as it uses the :random.uniform function from Erlang which is not suitable for generating secure random numbers. Also, it uses :erlang.now to seed the random number generator, which can be predictable and hence lead to generating predictable random numbers.
defmodule MyApp.TokenGenerator do
def generate_token do
:crypto.strong_rand_bytes(16) |> Base.encode16()
end
end
This secure code uses the :crypto.strong_rand_bytes function for generating a binary string of random bytes, which is then converted into a hexadecimal string using Base.encode16. This ensures the generation of secure random numbers.