Any library that generates a random URL safe string with the same seed?

If we always use the same seed then we always get the same number with :rand.uniform(10). I was wondering whether we can do that with random strings as well, I mean obviously we can but I was wondering whether there’s already that functionality in any library.

Why I need it is that, I need to create an API, and you don’t keep any data anywhere except encoding into the API token. Given the same API token you always have to generate the same information every time, so I thought using seeds would be a good approach.

One of them is this gist which actually uses Enum.random.

Not responding directly to your question, but it sounds like you want to hash something rather than generate a random value. I’d suggest looking into Plug.Crypto and JWTs.

1 Like

Yes, I am already using Plug.Crypto.sign/4 to generate an API token with some data. However I can not encode everything into the API token because then it will be huge and it doesn’t make sense to encode everything into the API token in my case.

So instead what I did is I am encoding a %{random_seed: 123} into the token and then using that seed I am generating numerical data for some fields and for some fields I need string data so I would also like to generate a string using the same seed so that every time I use the API token I will get the same results.

I think it’s also good to mention that random data is OK as far as it’s consistent which is what I am trying to do. Because this is going to be a sandbox API.

Maybe I’ll be using the gist I’ve shared above just to get going and I’ll figure it out later.

How do you generate the strings at the moment?

I didn’t have time to implement something to generate the strings but it seems like I will be using the gist I’ve shared above until I find something better. Someone also turned it into a package I guess:

The random string will be part of an id like foo_{RAND_STR_HERE} and then later it will be required to access that specific entity like /cars/:id

Simple generation of seeded, URL-safe strings (

Here is my attempt at modifying the gist for seeded generation. I took the liberty of simplifying the code a bit into a Livebook.

I don’t have any experience with :rand so I don’t know if you need to reset the seed generation to pseudo-random after generating in randomize/3, to prevent it affecting other parts of an application.

In my opinion it seems a bit overkill to create a whole library for this, but that’s not relevant to the question.

1 Like