How to generate a random url safe string with Elixir

后端 未结 3 1967
野的像风
野的像风 2021-02-05 00:47

I need to be able to generate random url safe strings so I could use those in links (like in an activation link sent to a user\'s email), so how can I generate it? Is there a wa

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 01:42

    As noted in @JimGray's comment, your specification should really be in terms of the amount of entropy you want to represent by the random URL safe strings. Something along the lines of "I need N bits" because someone told you to use N bits, or "I want to avoid repeat in N strings and I can accept a risk of 1 in n of a collision". Either way, it's directly about entropy and only indirectly about string length.

    For example, be sure that if you use a solution like @Gjaldon' answer you understand even though 512 bits of randomness is used, the amount of entropy for the actual string generated by random_string(64) is 320 bits. Whether that's sufficient is of course dependent on your scenario, which as noted above is probably best expressed as, for example, "I need a million strings with no more than a 1 in a trillion risk of repeat", in which case 320 bits is gross overkill as you'd only need 79.

    If you want more control and understanding of generating random strings, look at EntropyString. With that library, you could do something like the following to get a string with 256 bits of entropy:

    iex> defmodule Id, do: use EntropyString, charset: charset64
    iex> Id.token
    "ziKYK7t5LzVYn5XiJ_jYh30KxCCsLorRXqLwwEnZYHJ"
    

    Or if you realize a million strings with a repeat risk of 1 in a trillion is sufficient, you could set up your Id generation like:

    iex> defmodule Id do
    ...>   use EntropyString, charset: charset64
    ...>   @bits entropy_bits(1.0e6, 1.0e12)
    ...>   def random, do: Id.random_string(@bits)
    ...> end
    iex> Id.random
    "FhlGVXOaXV9f3f"
    

    Either way, control and understanding are nice things to have.

提交回复
热议问题