As shown in "Random State Initialization", in the GMP documentation, the only random generator algorithms included in GMP are—
- A Mersenne Twister algorithm,
- linear congruential generators of various sizes, and
- a "default algorithm" for "applications with no special requirements", including security requirements.
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:
- Build a list of characters allowed to appear in the random string.
- For each character in the string, call
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).