Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP rand() vs. random_int()

Tags:

php

php-7

As php.net indicates: random_int() function Generates cryptographically secure pseudo-random integers.

But, Can someone explain whats the difference between rand() & random_int()? Can I use random_int() instead of rand() when only requiring a random integer? Which one is faster?

like image 368
BehradKhodayar Avatar asked May 28 '17 15:05

BehradKhodayar


People also ask

Is PHP Random_int secure?

Unless speed is an issue, random_int() is the way to go but for the most basic non critical missions. Show activity on this post. As most number generators, using rand() is not secure because it does not generate cryptographically secure values and the output of rand() is predictable.

What is difference between Rand and Mt_rand in PHP?

The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

What is the use of rand () in PHP?

Definition and Usage The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

Is Mt_rand secure?

From http://php.net/manual/en/function.mt-rand.php: Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.


1 Answers

Revisiting the question and seeing there's been an answer given, I find it's only fair that I submit my comments to an answer, seeing they were submitted before.

The manual on PHP 7's random_int() function states:

"Returns a cryptographically secure random integer in the range min to max, inclusive."

  • http://php.net/manual/en/function.random-int.php

and for rand()

*This function does not generate cryptographically secure values" *

  • http://php.net/manual/en/function.rand.php

OP's comment:

"@Fred-ii- thank you. But what does "cryptographically secure pseudo-random" mean? – NDFA"

That can be found in the following links as per my findings:

  • https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator

Which states:

A cryptographically secure pseudo-random number generator (CSPRNG) or cryptographic pseudo-random number generator (CPRNG)[1] is a pseudo-random number generator (PRNG) with properties that make it suitable for use in cryptography.


  • How does a cryptographically secure random number generator work?

In regards to performance, you will need to run a benchmark yourself.

like image 148
Funk Forty Niner Avatar answered Sep 17 '22 14:09

Funk Forty Niner