SecureRandom.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. *
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OC\Security;
  25. use OCP\Security\ISecureRandom;
  26. /**
  27. * Class SecureRandom provides a wrapper around the random_int function to generate
  28. * secure random strings. For PHP 7 the native CSPRNG is used, older versions do
  29. * use a fallback.
  30. *
  31. * Usage:
  32. * \OC::$server->getSecureRandom()->generate(10);
  33. * @package OC\Security
  34. */
  35. class SecureRandom implements ISecureRandom {
  36. /**
  37. * Generate a random string of specified length.
  38. * @param int $length The length of the generated string
  39. * @param string $characters An optional list of characters to use if no character list is
  40. * specified all valid base64 characters are used.
  41. * @return string
  42. */
  43. public function generate(int $length,
  44. string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string {
  45. $maxCharIndex = \strlen($characters) - 1;
  46. $randomString = '';
  47. while($length > 0) {
  48. $randomNumber = \random_int(0, $maxCharIndex);
  49. $randomString .= $characters[$randomNumber];
  50. $length--;
  51. }
  52. return $randomString;
  53. }
  54. }