note 83655 added to function.mt-rand
| From: | MarkSeecof at osu1 dot php dot net | Date: | Fri, 06 Jun 2008 06:31:15 +0000 |
| Subject: | note 83655 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140165@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 209.41.74.194
Probable Submitter: 75.84.67.109
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/83655
Del: integrated -- https://master.php.net/note/delete/83655/integrated
Del: useless -- https://master.php.net/note/delete/83655/useless
Del: bad code -- https://master.php.net/note/delete/83655/bad+code
Del: spam -- https://master.php.net/note/delete/83655/spam
Del: non-english -- https://master.php.net/note/delete/83655/non-english
Del: in docs -- https://master.php.net/note/delete/83655/in+docs
Del: other reasons-- https://master.php.net/note/delete/83655
Reject -- https://master.php.net/note/reject/83655
Search -- https://master.php.net/manage/user-notes.php