Secure Random Numbers in Elixir (and Erlang)

I’ve been working with a problem involving cryptography recently, which requires cryptographically secure random numbers. This post is my exploration into how to generate secure random numbers with Elixir.

9 Likes

Playing with the concept, we could make a super simple wrapper library that provides sensible defaults.

defmodule Crypto do
  def random_bytes(n) do
    :crypto.strong_rand_bytes(n)
  end

  def random_integer(n) do
    {int, _unused_seed} = :rand.uniform_s(n, :crypto.rand_seed_s())
    int
  end

  def random_float() do
    {float, _unused_seed} = :rand.uniform_real_s(:crypto.rand_seed_s())
    float
  end
end
iex(1)> Crypto.random_bytes(10)
<<231, 232, 192, 181, 115, 153, 116, 24, 141, 158>>
iex(2)> Crypto.random_integer(10)
6
iex(3)> Crypto.random_float()
0.21388785742247599
2 Likes

Nice writeup. Thanks for sharing.

1 Like