1
0

SecureRandom.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 secure 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. * @throws \LengthException if an invalid length is requested
  44. */
  45. public function generate(
  46. int $length,
  47. string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
  48. ): string {
  49. if ($length <= 0) {
  50. throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
  51. }
  52. $maxCharIndex = \strlen($characters) - 1;
  53. $randomString = '';
  54. while ($length > 0) {
  55. $randomNumber = \random_int(0, $maxCharIndex);
  56. $randomString .= $characters[$randomNumber];
  57. $length--;
  58. }
  59. return $randomString;
  60. }
  61. }