PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/zendframework/zendframework/library/Zend/Math/Rand.php

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