I use PHP to write a software that generates random combinations of characters. For this I need arbitrary length integers random generation. So I use GMP extension and especially gmp_random_range(). But I need to prove with a link for example that it is cryptographically secure. Or at least it is enough random.
GMP random functions use seed (gmp_random_seed ), and if I don't set a seed everything looks random enough. So, I suppose when I don't set the seed explicitly it takes it from some reliable random source. I could not find something clearly stating such thing.
As shown in "Random State Initialization", in the GMP documentation, the only random generator algorithms included in GMP are—
Curiously, the GMP documentation says in "Random State Seeding" that the "method for choosing a seed is critical if the generated numbers are to be used for important applications, such as generating cryptographic keys", even though none of the algorithms included in GMP are appropriate for cryptographic use.
As it appears, you can use random_bytes
or random_int
in PHP to generate cryptographic random numbers. The only thing left is to transform the numbers they deliver into arbitrary-precision numbers.* In that sense, GMP appears not to allow custom RNGs (besides the ones it provides) for the gmp_random_range
and similar functions. Thus, you will have to transform those random numbers "manually", with the help of GMP's arithmetic functions. I have an article that discusses how to transform random numbers into a variety of distributions. To generate uniform random integers in a given range, the algorithm you need is called RNDINT
or RNDINTEXC
in that article.
* Where information security is involved, using random numbers as the seed for a noncryptographic RNG is not appropriate since an attacker, given enough random numbers, can then work backwards to derive the seed, even if the seed was generated in a cryptographically secure way.
If your goal is merely to generate a cryptographically random string of characters, you don't even need to go the GMP route. Just build the string one character at a time by calling random_int
for each character you want to generate:
random_int
with a max of the list's size (a size which will almost certainly be within the range of integers PHP can handle), then append the character found at the given random index in the list (starting at 0).