MTRand.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * The RandomLib library for securely generating random numbers and strings in PHP
  4. *
  5. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  6. * @copyright 2011 The Authors
  7. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  8. * @version Build @@version@@
  9. */
  10. /**
  11. * The MTRand Random Number Source
  12. *
  13. * This source generates low strength random numbers by using the internal
  14. * mt_rand() function. By itself it is quite weak. However when combined with
  15. * other sources it does provide significant benefit.
  16. *
  17. * PHP version 5.3
  18. *
  19. * @category PHPCryptLib
  20. * @package Random
  21. * @subpackage Source
  22. *
  23. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  24. * @author Paragon Initiative Enterprises <security@paragonie.com>
  25. * @copyright 2011 The Authors
  26. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  27. *
  28. * @version Build @@version@@
  29. */
  30. namespace RandomLib\Source;
  31. use SecurityLib\Strength;
  32. /**
  33. * The MTRand Random Number Source
  34. *
  35. * This source generates low strength random numbers by using the internal
  36. * mt_rand() function. By itself it is quite weak. However when combined with
  37. * other sources it does provide significant benefit.
  38. *
  39. * @category PHPCryptLib
  40. * @package Random
  41. * @subpackage Source
  42. *
  43. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  44. * @author Paragon Initiative Enterprises <security@paragonie.com>
  45. * @codeCoverageIgnore
  46. */
  47. class MTRand extends \RandomLib\AbstractSource
  48. {
  49. /**
  50. * Return an instance of Strength indicating the strength of the source
  51. *
  52. * @return \SecurityLib\Strength An instance of one of the strength classes
  53. */
  54. public static function getStrength()
  55. {
  56. // Detect if Suhosin Hardened PHP patch is applied
  57. if (defined('S_ALL')) {
  58. return new Strength(Strength::LOW);
  59. } else {
  60. return new Strength(Strength::VERYLOW);
  61. }
  62. }
  63. /**
  64. * Generate a random string of the specified size
  65. *
  66. * @param int $size The size of the requested random string
  67. *
  68. * @return string A string of the requested size
  69. */
  70. public function generate($size)
  71. {
  72. $result = '';
  73. for ($i = 0; $i < $size; $i++) {
  74. $result .= chr((mt_rand() ^ mt_rand()) % 256);
  75. }
  76. return $result;
  77. }
  78. }