You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SecureRandom.php 1.9KB

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