Possible Duplicate:
Secure random number generation in PHP
We need to generate a cryptographically random string to use as an authentication token, which will be tied to session data in the database. We are using PHP, which doesn't appear to have a suitable random number generator built-in. How can we generate a cryptographically secure random string of N length using php?
Also note, due to the nature of our application, shell_exec is off the table.
A PRNG is said to be cryptographically secure if, assuming that it operates over a wide enough unknown n-bit key, its output is computationally indistinguishable from uniformly random bits.
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.
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) !=
Depending on your platform, you may use /dev/urandom or CAPICOM. This is nicely summarized in this comment from Mark Seecof:
"If you need some pseudorandom bits for security or cryptographic purposes (e.g.g., random IV for block cipher, random salt for password hash) mt_rand() is a poor source. On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this:
<?php // get 128 pseudorandom bits in a string of 16 bytes $pr_bits = ''; // Unix/Linux platform? $fp = @fopen('/dev/urandom','rb'); if ($fp !== FALSE) { $pr_bits .= @fread($fp,16); @fclose($fp); } // MS-Windows platform? if (@class_exists('COM')) { // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx try { $CAPI_Util = new COM('CAPICOM.Utilities.1'); $pr_bits .= $CAPI_Util->GetRandom(16,0); // if we ask for binary data PHP munges it, so we // request base64 return value. We squeeze out the // redundancy and useless ==CRLF by hashing... if ($pr_bits) { $pr_bits = md5($pr_bits,TRUE); } } catch (Exception $ex) { // echo 'Exception: ' . $ex->getMessage(); } } if (strlen($pr_bits) < 16) { // do something to warn system owner that // pseudorandom generator is missing } ?>
NB: it is generally safe to leave both the attempt to read /dev/urandom and the attempt to access CAPICOM in your code, though each will fail silently on the other's platform. Leave them both there so your code will be more portable."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With