Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random alphanumeric string with Erlang?

I'm trying to generate an random alphanumeric ID with Erlang. I naively tried crypto:strong_rand_bytes(Bytes) to generate a random binary and then used that binary like it was created with <<"my_unique_random_id">> - which didn't work because random bits are not necessarily a valid UTF-8 string, right?

Well, I looked for other options in the erlang docs and elsewhere, but I didn't find anything. Could someone point me to a solution?

like image 529
Max Merz Avatar asked Oct 08 '12 20:10

Max Merz


2 Answers

It might depend on the randomness you need. Erlang's crypto module produces stronger random data than the random module (see also [erlang-questions] Yaws security alert - Yaws 1.93 and this question). If you want to use strong_rand_bytes to generate an ID maybe getting the base64 of it might be enough:

> base64:encode(crypto:strong_rand_bytes(Bytes)).

You could turn this into a list if needed.

like image 140
Tilman Avatar answered Dec 22 '22 14:12

Tilman


According to Generating random strings in Erlang it only takes a few lines of Erlang to generate a string of a specified length from a certain set of characters.

get_random_string(Length, AllowedChars) ->
    lists:foldl(fun(_, Acc) ->
                        [lists:nth(random:uniform(length(AllowedChars)),
                                   AllowedChars)]
                            ++ Acc
                end, [], lists:seq(1, Length)).

The blog post has a line-by-line explanation of the code. Look to the comments for a couple of optimization tips.

like image 33
Bill the Lizard Avatar answered Dec 22 '22 16:12

Bill the Lizard