Rand.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 Rand Random Number Source
  12. *
  13. * This source generates low strength random numbers by using the internal
  14. * 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. * @copyright 2011 The Authors
  25. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  26. *
  27. * @version Build @@version@@
  28. */
  29. namespace RandomLib\Source;
  30. use SecurityLib\Strength;
  31. /**
  32. * The Rand Random Number Source
  33. *
  34. * This source generates low strength random numbers by using the internal
  35. * rand() function. By itself it is quite weak. However when combined with
  36. * other sources it does provide significant benefit.
  37. *
  38. * @category PHPCryptLib
  39. * @package Random
  40. * @subpackage Source
  41. *
  42. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  43. * @codeCoverageIgnore
  44. */
  45. class Rand extends \RandomLib\AbstractSource
  46. {
  47. /**
  48. * Return an instance of Strength indicating the strength of the source
  49. *
  50. * @return \SecurityLib\Strength An instance of one of the strength classes
  51. */
  52. public static function getStrength()
  53. {
  54. // Detect if Suhosin Hardened PHP patch is applied
  55. if (defined('S_ALL')) {
  56. return new Strength(Strength::LOW);
  57. } else {
  58. return new Strength(Strength::VERYLOW);
  59. }
  60. }
  61. /**
  62. * Generate a random string of the specified size
  63. *
  64. * @param int $size The size of the requested random string
  65. *
  66. * @return string A string of the requested size
  67. */
  68. public function generate($size)
  69. {
  70. $result = '';
  71. for ($i = 0; $i < $size; $i++) {
  72. $result .= chr((rand() ^ rand()) % 256);
  73. }
  74. return $result;
  75. }
  76. }