RandomBytes.php 2.1 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 PHP7 Random Number Source
  12. *
  13. * This uses the inbuilt PHP7 Random Bytes function
  14. *
  15. * PHP version 5.3
  16. *
  17. * @category PHPCryptLib
  18. * @package Random
  19. * @subpackage Source
  20. *
  21. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  22. * @author Paragon Initiative Enterprises <security@paragonie.com>
  23. * @copyright 2011 The Authors
  24. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  25. *
  26. * @version Build @@version@@
  27. */
  28. namespace RandomLib\Source;
  29. use SecurityLib\Strength;
  30. /**
  31. * The PHP7 Random Number Source
  32. *
  33. * This uses the php7 secure generator to generate high strength numbers
  34. *
  35. * @category PHPCryptLib
  36. * @package Random
  37. * @subpackage Source
  38. *
  39. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  40. * @author Paragon Initiative Enterprises <security@paragonie.com>
  41. */
  42. class RandomBytes extends \RandomLib\AbstractSource
  43. {
  44. /**
  45. * If the source is currently available.
  46. * Reasons might be because the library is not installed
  47. *
  48. * @return bool
  49. */
  50. public static function isSupported()
  51. {
  52. return \is_callable('random_bytes');
  53. }
  54. /**
  55. * Return an instance of Strength indicating the strength of the source
  56. *
  57. * @return Strength An instance of one of the strength classes
  58. */
  59. public static function getStrength()
  60. {
  61. return new Strength(Strength::HIGH);
  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. if (!self::isSupported()) {
  73. return \str_repeat(chr(0), $size);
  74. }
  75. return \random_bytes($size);
  76. }
  77. }