PageRenderTime 58ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Math/Rand.php

https://bitbucket.org/vnagara/zendframework
PHP | 176 lines | 98 code | 13 blank | 65 comment | 19 complexity | 50fe788e580d4bdbe7dc494eceeb66f2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. * @package Zend_Math
  9. */
  10. namespace Zend\Math;
  11. /**
  12. * Pseudorandom number generator (PRNG)
  13. *
  14. * @category Zend
  15. * @package Zend_Math
  16. * @subpackage Rand
  17. */
  18. abstract class Rand
  19. {
  20. /**
  21. * Generate random bytes using OpenSSL or Mcrypt and mt_rand() as fallback
  22. *
  23. * @param integer $length
  24. * @param boolean $strong true if you need a strong random generator (cryptography)
  25. * @return string
  26. * @throws Exception\RuntimeException
  27. */
  28. public static function getBytes($length, $strong = false)
  29. {
  30. if ($length <= 0) {
  31. return false;
  32. }
  33. if (extension_loaded('openssl')) {
  34. $rand = openssl_random_pseudo_bytes($length, $secure);
  35. if ($secure === true) {
  36. return $rand;
  37. }
  38. }
  39. if (extension_loaded('mcrypt')) {
  40. // PHP bug #55169
  41. // @see https://bugs.php.net/bug.php?id=55169
  42. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' ||
  43. version_compare(PHP_VERSION, '5.3.7') >= 0) {
  44. $rand = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  45. if ($rand !== false && strlen($rand) === $length) {
  46. return $rand;
  47. }
  48. }
  49. }
  50. if ($strong) {
  51. throw new Exception\RuntimeException(
  52. 'This PHP environment doesn\'t support secure random number generation. ' .
  53. 'Please consider to install the OpenSSL and/or Mcrypt extensions'
  54. );
  55. }
  56. $rand = '';
  57. for ($i = 0; $i < $length; $i++) {
  58. $rand .= chr(mt_rand(0, 255));
  59. }
  60. return $rand;
  61. }
  62. /**
  63. * Generate random boolean
  64. *
  65. * @param boolean $strong true if you need a strong random generator (cryptography)
  66. * @return bool
  67. */
  68. public static function getBoolean($strong = false)
  69. {
  70. $byte = static::getBytes(1, $strong);
  71. return (boolean) (ord($byte) % 2);
  72. }
  73. /**
  74. * Generate a random integer between $min and $max
  75. *
  76. * @param integer $min
  77. * @param integer $max
  78. * @param boolean $strong true if you need a strong random generator (cryptography)
  79. * @return integer
  80. * @throws Exception\DomainException
  81. */
  82. public static function getInteger($min, $max, $strong = false)
  83. {
  84. if ($min > $max) {
  85. throw new Exception\DomainException(
  86. 'The min parameter must be lower than max parameter'
  87. );
  88. }
  89. $range = $max - $min;
  90. if ($range == 0) {
  91. return $max;
  92. } elseif ($range > PHP_INT_MAX || is_float($range)) {
  93. throw new Exception\DomainException(
  94. 'The supplied range is too great to generate'
  95. );
  96. }
  97. $log = log($range, 2);
  98. $bytes = (int) ($log / 8) + 1;
  99. $bits = (int) $log + 1;
  100. $filter = (int) (1 << $bits) - 1;
  101. do {
  102. $rnd = hexdec(bin2hex(self::getBytes($bytes, $strong)));
  103. $rnd = $rnd & $filter;
  104. } while ($rnd > $range);
  105. return ($min + $rnd);
  106. }
  107. /**
  108. * Generate random float (0..1)
  109. * This function generates floats with platform-dependent precision
  110. *
  111. * PHP uses double precision floating-point format (64-bit) which has
  112. * 52-bits of significand precision. We gather 7 bytes of random data,
  113. * and we fix the exponent to the bias (1023). In this way we generate
  114. * a float of 1.mantissa.
  115. *
  116. * @param boolean $strong true if you need a strong random generator (cryptography)
  117. * @return float
  118. */
  119. public static function getFloat($strong = false)
  120. {
  121. $bytes = static::getBytes(7, $strong);
  122. $bytes[6] = $bytes[6] | chr(0xF0);
  123. $bytes .= chr(63); // exponent bias (1023)
  124. list(, $float) = unpack('d', $bytes);
  125. return ($float - 1);
  126. }
  127. /**
  128. * Generate a random string of specified length.
  129. *
  130. * Uses supplied character list for generating the new string.
  131. * If no character list provided - uses Base 64 character set.
  132. *
  133. * @param integer $length
  134. * @param string|null $charlist
  135. * @param boolean $strong true if you need a strong random generator (cryptography)
  136. * @return string
  137. * @throws Exception\DomainException
  138. */
  139. public static function getString($length, $charlist = null, $strong = false)
  140. {
  141. if ($length < 1) {
  142. throw new Exception\DomainException('Length should be >= 1');
  143. }
  144. // charlist is empty or not provided
  145. if (empty($charlist)) {
  146. $numBytes = ceil($length * 0.75);
  147. $bytes = static::getBytes($numBytes);
  148. return substr(rtrim(base64_encode($bytes), '='), 0, $length);
  149. }
  150. $listLen = strlen($charlist);
  151. if ($listLen == 1) {
  152. return str_repeat($charlist, $length);
  153. }
  154. $bytes = static::getBytes($length, $strong);
  155. $pos = 0;
  156. $result = '';
  157. for ($i = 0; $i < $length; $i++) {
  158. $pos = ($pos + ord($bytes[$i])) % $listLen;
  159. $result .= $charlist[$pos];
  160. }
  161. return $result;
  162. }
  163. }